734_D. Anton and Chess

Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.

The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.

Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move.

Help Anton and write the program that for the given position determines whether the white king is in check.

Remainder, on how do chess pieces move:

  * Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells.
  * Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells.
  * Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap".

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of black pieces.

The second line contains two integers x0 and y0 ( - 109 ≤ x0, y0 ≤ 109) — coordinates of the white king.

Then follow n lines, each of them contains a character and two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — type of the i-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position.

Output

The only line of the output should contains "YES" (without quotes) if the white king is in check and "NO" (without quotes) otherwise.

Examples

Input

2
4 2
R 1 1
B 1 5

Output

YES

Input

2
4 2
R 3 3
B 1 5

Output

NO

Note

Picture for the first sample:

<image> White king is in check, because the black bishop can reach the cell with the white king in one move. The answer is "YES".

Picture for the second sample:

<image> Here bishop can't reach the cell with the white king, because his path is blocked by the rook, and the bishop cant "leap" over it. Rook can't reach the white king, because it can't move diagonally. Hence, the king is not in check and the answer is "NO".

```python
MAX_NUM = 10**9
n = int(input())
king_x, king_y = [int(x) for x in input().split()]
nomakers = {'Rook': {'right-down':[], 'right-up':[], 'left-down':[], 'left-up':[]}, 'Bishop': {'left':[], 'right':[], 'up':[], 'down':[]}}
yes = {'Queen':{'right-down':[], 'right-up':[], 'left-down':[], 'left-up':[],'left':[], 'right':[], 'up':[], 'down':[]},'Bishop': {'right-down':[], 'right-up':[], 'left-down':[], 'left-up':[]}, 'Rook': {'left':[], 'right':[], 'up':[], 'down':[]}}
for i in range(n):
    figure, figure_x, figure_y = input().split()
    figure_x, figure_y = [int(x) for x in [figure_x, figure_y]]
    if figure == 'Q':
        if figure_x == king_x:
            if figure_y < king_y: half = 'down'
            else: half = 'up'
            yes['Queen'][half].append(abs(king_y - figure_y))
            for i in range(len(nomakers['Bishop'][half])):
                if nomakers['Bishop'][half][i]<yes['Queen'][half][-1]:
                    del yes['Queen'][half][-1]
                    break
        elif figure_y == king_y:
            if figure_x < king_x: half = 'left'
            else: half = 'right'
            yes['Queen'][half].append(abs(king_x - figure_x))
            for i in range(len(nomakers['Bishop'][half])):
                if nomakers['Bishop'][half][i]<yes['Queen'][half][-1]:
                    del yes['Queen'][half][-1]
                    break
        elif abs(figure_x - king_x) == abs(figure_y - king_y):
            if figure_x > king_x:
                if figure_y > king_y: quarter = 'right-up'
                else: quarter = 'right-down'
            else:
                if figure_y > king_y: quarter = 'left-up'
                else: quarter = 'left-down'
            yes['Queen'][quarter].append(abs(king_x - figure_x))
            for i in range(len(nomakers['Rook'][quarter])):
                if nomakers['Rook'][quarter][i]<yes['Queen'][quarter][-1]:
                    del yes['Queen'][quarter][-1]
                    break
    elif figure == 'R':
        if figure_x == king_x:
            if figure_y < king_y: half = 'down'
            else: half = 'up'
            yes['Rook'][half].append(abs(king_y - figure_y))
            for i in range(len(nomakers['Bishop'][half])):
                if nomakers['Bishop'][half][i]<yes['Rook'][half][-1]:
                    del yes['Rook'][half][-1]
                    break
        elif figure_y == king_y:
            if figure_x > king_x: half = 'right'
            else: half = 'left'
            yes['Rook'][half].append(abs(king_x - figure_x))
            for i in range(len(nomakers['Bishop'][half])):
                if nomakers['Bishop'][half][i]<yes['Rook'][half][-1]:
                    del yes['Rook'][half][-1]
                    break
        elif abs(figure_x - king_x) == abs(figure_y - king_y):
            if figure_x > king_x:
                if figure_y > king_y: quarter = 'right-up'
                else: quarter = 'right-down'
            else:
                if figure_y > king_y: quarter = 'left-up'
                else: quarter = 'left-down'
            nomakers['Rook'][quarter].append(abs(figure_x - king_x))
            i = 0
            n = len(yes['Queen'][quarter])
            while i < n:
                element = yes['Queen'][quarter][i]
                if nomakers['Rook'][quarter][-1] < element:
                    del yes['Queen'][quarter][i]
                    n = n - 1
                else:
                    i = i + 1
            i = 0
            n = len(yes['Bishop'][quarter])
            while i < n:
                element = yes['Bishop'][quarter][i]
                if nomakers['Rook'][quarter][-1] < element:
                    del yes['Bishop'][quarter][i]
                    n = n - 1
                else:
                    i = i + 1
    else:
        if abs(figure_x - king_x) == abs(figure_y - king_y):
            if figure_x > king_x:
                if figure_y > king_y: quarter = 'right-up'
                else: quarter = 'right-down'
            else:
                if figure_y > king_y: quarter = 'left-up'
                else: quarter = 'left-down'
            yes['Bishop'][quarter].append(abs(figure_x - king_x))
            for i in range(len(nomakers['Rook'][quarter])):
                if nomakers['Rook'][quarter][i] < yes['Bishop'][quarter][-1]:
                    del yes['Bishop'][quarter][-1]
                    break
        elif figure_x == king_x or figure_y == king_y:
            if figure_y < king_y:
                a = figure_y - king_y
                half = 'down'
            elif figure_y > king_y:
                half = 'up'
                a = figure_y - king_y
            elif figure_x > king_x:
                a = figure_x - king_x
                half = 'right'
            else:
                a = figure_x - king_x
                half = 'left'
            nomakers['Bishop'][half].append(abs(a))
            i = 0
            n = len(yes['Rook'][half])
            while i < n:
                element = yes['Rook'][half][i]
                if nomakers['Bishop'][half][-1] < element:
                    del yes['Rook'][half][i]
                    n = n - 1
                else:
                    i = i + 1
            i = 0
            n = len(yes['Queen'][half])
            while i < n:
                element = yes['Queen'][half][i]
                if nomakers['Bishop'][half][-1] < element:
                    del yes['Queen'][half][i]
                    n = n - 1
                else:
                    i = i + 1
if len(yes['Queen']['left']) > 0 or len(yes['Queen']['right']) > 0 or len(yes['Queen']['down']) > 0 or len(yes['Queen']['up']) > 0 or len(yes['Queen']['left-up']) > 0 or len(yes['Queen']['left-down']) > 0 or len(yes['Queen']['right-up']) > 0 or len(yes['Queen']['right-down']) > 0 or len(yes['Bishop']['right-down']) > 0 or len(yes['Bishop']['right-up']) > 0 or len(yes['Bishop']['left-up']) > 0 or len(yes['Bishop']['left-down']) > 0 or len(yes['Rook']['left']) > 0 or len(yes['Rook']['right']) > 0 or len(yes['Rook']['up']) > 0 or len(yes['Rook']['down']) > 0:
    print("YES")
else: print("NO")
```


758_D. Ability To Convert

Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets 11311 (475 = 1·162 + 13·161 + 11·160). Alexander lived calmly until he tried to convert the number back to the decimal number system.

Alexander remembers that he worked with little numbers so he asks to find the minimum decimal number so that by converting it to the system with the base n he will get the number k.

Input

The first line contains the integer n (2 ≤ n ≤ 109). The second line contains the integer k (0 ≤ k < 1060), it is guaranteed that the number k contains no more than 60 symbols. All digits in the second line are strictly less than n.

Alexander guarantees that the answer exists and does not exceed 1018.

The number k doesn't contain leading zeros.

Output

Print the number x (0 ≤ x ≤ 1018) — the answer to the problem.

Examples

Input

13
12

Output

12

Input

16
11311

Output

475

Input

20
999

Output

3789

Input

17
2016

Output

594

Note

In the first example 12 could be obtained by converting two numbers to the system with base 13: 12 = 12·130 or 15 = 1·131 + 2·130.

```python
n = input()
k = input()
digit = len(n)
lst = []
def recul(k):
	if len(k)== 0:
		return
	if k[-digit:] < n:
			lst.append(k[-digit:])
			if k[-digit:][0:1] == '0' and len(k[-digit:]) != 1:
				recul(k[:-digit]+'0')
			else:
				recul(k[:-digit])
	else:
		temp = -digit+1
		while k[temp:temp+1]== '0' and temp<0:
			temp += 1
		if temp == 0:
			lst.append('0')
			recul(k[:-1])
			return
		lst.append(k[temp:])
		recul(k[:temp])
if digit == 1:
	print(int(k,int(n)))
	exit()
recul(k)
ans = 0
for x in range(len(lst)):
	 ans += int(lst[x])*int(n)**x
print(ans)

```


77_B. Falling Anvils

For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.

Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!

It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.

Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root:

<image>

Determine the probability with which an aim can be successfully hit by an anvil.

You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.

Input

The first line contains integer t (1 ≤ t ≤ 10000) — amount of testcases.

Each of the following t lines contain two space-separated integers a and b (0 ≤ a, b ≤ 106).

Pretests contain all the tests with 0 < a < 10, 0 ≤ b < 10.

Output

Print t lines — the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.

Examples

Input

2
4 2
1 2

Output

0.6250000000
0.5312500000

```python
t = int(input())
for _ in range(t):
  a, b = map(int, input().split())
  if a == 0 and b == 0:
    print(1)
  elif a == 0:
    print(0.5)
  elif b == 0:
    print(1)
  elif a > 4 * b:
    print('%.10f' % ((a - b) / a))
  else:
    print('%.10f' % (a / 16 / b + 0.5))

```


803_A. Maximal Binary Matrix

You are given matrix with n rows and n columns filled with zeroes. You should put k ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.

One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.

If there exists no such matrix then output -1.

Input

The first line consists of two numbers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 106).

Output

If the answer exists then output resulting matrix. Otherwise output -1.

Examples

Input

2 1

Output

1 0
0 0

Input

3 2

Output

1 0 0
0 1 0
0 0 0

Input

2 5

Output

-1

```python
import sys
import bisect
from bisect import bisect_left as lb
input_=lambda: sys.stdin.readline().strip("\r\n")
from math import log
from math import gcd
from math import atan2,acos
from random import randint
sa=lambda :input_()
sb=lambda:int(input_())
sc=lambda:input_().split()
sd=lambda:list(map(int,input_().split()))
sflo=lambda:list(map(float,input_().split()))
se=lambda:float(input_())
sf=lambda:list(input_())
flsh=lambda: sys.stdout.flush()
#sys.setrecursionlimit(10**6)
mod=10**9+7
mod1=998244353
gp=[]
cost=[]
dp=[]
mx=[]
ans1=[]
ans2=[]
special=[]
specnode=[]
a=0
kthpar=[]
def dfs(root,par):
    if par!=-1:
        dp[root]=dp[par]+1
    for i in range(1,20):
        if kthpar[root][i-1]!=-1:
            kthpar[root][i]=kthpar[kthpar[root][i-1]][i-1]
    for child in gp[root]:
        if child==par:continue
        kthpar[child][0]=root
        dfs(child,root)
ans=0
def hnbhai(tc):
    n,k=sd()
    mat=[[0 for i in range(n)]for j in range(n)]
    if n*n<k:
        print(-1)
        return
    for i in range(n):
        for j in range(n):
            if i==j and k>0:
                mat[i][j]=1
                k-=1
            elif j>i and k>1:
                mat[i][j]=1
                mat[j][i]=1
                k-=2
    if k:
        print(-1)
        return
    for i in mat:
        print(*i)
for _ in range(1):
    hnbhai(_+1)

```


898_B. Proper Nutrition

Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.

Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.

In other words, you should find two non-negative integers x and y such that Vasya can buy x bottles of Ber-Cola and y Bars bars and x·a + y·b = n or tell that it's impossible.

Input

First line contains single integer n (1 ≤ n ≤ 10 000 000) — amount of money, that Vasya has.

Second line contains single integer a (1 ≤ a ≤ 10 000 000) — cost of one bottle of Ber-Cola.

Third line contains single integer b (1 ≤ b ≤ 10 000 000) — cost of one Bars bar.

Output

If Vasya can't buy Bars and Ber-Cola in such a way to spend exactly n burles print «NO» (without quotes).

Otherwise in first line print «YES» (without quotes). In second line print two non-negative integers x and y — number of bottles of Ber-Cola and number of Bars bars Vasya should buy in order to spend exactly n burles, i.e. x·a + y·b = n. If there are multiple answers print any of them.

Any of numbers x and y can be equal 0.

Examples

Input

7
2
3

Output

YES
2 1

Input

100
25
10

Output

YES
0 10

Input

15
4
8

Output

NO

Input

9960594
2551
2557

Output

YES
1951 1949

Note

In first example Vasya can buy two bottles of Ber-Cola and one Bars bar. He will spend exactly 2·2 + 1·3 = 7 burles.

In second example Vasya can spend exactly n burles multiple ways:

  * buy two bottles of Ber-Cola and five Bars bars;
  * buy four bottles of Ber-Cola and don't buy Bars bars;
  * don't buy Ber-Cola and buy 10 Bars bars.

In third example it's impossible to but Ber-Cola and Bars bars in order to spend exactly n burles.

```python
n = int(input())
a = int(input())
b = int(input())
for i in range(n//a+1):
  if (n - i * a) % b == 0:
    print("YES")
    print(i, (n - i * a) // b)
    break
else: print("NO")

```


919_C. Seat Arrangements

Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.

The classroom contains n rows of seats and there are m seats in each row. Then the classroom can be represented as an n × m matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find k consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.

Input

The first line contains three positive integers n,m,k (1 ≤ n, m, k ≤ 2 000), where n,m represent the sizes of the classroom and k is the number of consecutive seats you need to find.

Each of the next n lines contains m characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.

Output

A single number, denoting the number of ways to find k empty seats in the same row or column.

Examples

Input

2 3 2
**.
...

Output

3

Input

1 2 2
..

Output

1

Input

3 3 4
.*.
*.*
.*.

Output

0

Note

In the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement.

  * (1,3), (2,3)
  * (2,2), (2,3)
  * (2,1), (2,2)

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

def count(M):
    nr = len(M)
    nc = len(M[0])
    res = 0
    for i in range(nr):
        j = 0
        while j < nc:
            while j < nc and M[i][j] == '*':
                j += 1
            j2 = j
            while j2 < nc and M[i][j2] == '.':
                j2 += 1
            res += max(0, j2 - j - k +1)
            j = j2
    return res

def transpose(M):
    nr = len(M)
    nc = len(M[0])
    T = list()
    for j in range(nc):
        s = list()
        for i in range(nr):
            s.append(M[i][j])
        T.append(s)
    return T

M = list()
for i in range(n):
    M.append(input().strip())
res = count(M)
if k > 1:
    res += count(transpose(M))
print(res)

```


946_B. Weird Subtraction Process

You have two variables a and b. Consider the following sequence of actions performed with these variables:

  1. If a = 0 or b = 0, end the process. Otherwise, go to step 2;
  2. If a ≥ 2·b, then set the value of a to a - 2·b, and repeat step 1. Otherwise, go to step 3;
  3. If b ≥ 2·a, then set the value of b to b - 2·a, and repeat step 1. Otherwise, end the process.

Initially the values of a and b are positive integers, and so the process will be finite.

You have to determine the values of a and b after the process ends.

Input

The only line of the input contains two integers n and m (1 ≤ n, m ≤ 1018). n is the initial value of variable a, and m is the initial value of variable b.

Output

Print two integers — the values of a and b after the end of the process.

Examples

Input

12 5

Output

0 1

Input

31 12

Output

7 12

Note

Explanations to the samples:

  1. a = 12, b = 5 <image> a = 2, b = 5 <image> a = 2, b = 1 <image> a = 0, b = 1;
  2. a = 31, b = 12 <image> a = 7, b = 12.

```python
a, b = map(int, input().split())
while a != 0 and b != 0:
    if a >= 2 * b:
        a = a % (2 * b)
    elif b >= 2 * a:
        b = b % (2 * a)
    else:
        print(a, b)
        exit(0)
print(a, b)

```


994_E. Careful Maneuvering

There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.

Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.

The second line contains n integers y_{1,1}, y_{1,2}, …, y_{1,n} (|y_{1,i}| ≤ 10 000) — the y-coordinates of the spaceships in the first group.

The third line contains m integers y_{2,1}, y_{2,2}, …, y_{2,m} (|y_{2,i}| ≤ 10 000) — the y-coordinates of the spaceships in the second group.

The y coordinates are not guaranteed to be unique, even within a group.

Output

Print a single integer – the largest number of enemy spaceships that can be destroyed.

Examples

Input

3 9
1 2 3
1 2 3 7 8 9 11 12 13

Output

9

Input

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

Output

10

Note

In the first example the first spaceship can be positioned at (0, 2), and the second – at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.

In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.

```python
from collections import defaultdict
import itertools as it

def main():
	n, m = map(int, input().split())

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

	p2d = defaultdict(lambda :set())

	for i, ll in enumerate(l):
		for j, rr in enumerate(r, len(l)):
			pd = p2d[(ll+rr)/2]
			pd.add(i)
			pd.add(j)

	ps = sorted(p2d, key=lambda p:-len(p2d[p]))
	lenps = len(ps)
	stop = lenps-1
	best = len(p2d[ps[0]])

	for i1, p1 in enumerate(ps):
		dp1 = p2d[p1]
		lendp1 = len(dp1)
		if i1 == stop or lendp1 + len(p2d[ps[i1+1]]) <= best:
			break
		best_second = 0
		for i2 in range(i1+1, lenps):
			p2 = ps[i2]
			dp2 = p2d[p2]
			if len(dp2) < best_second:
				break
			p2_addition = 0
			for ship in dp2:
				p2_addition += ship not in dp1
			new_best = lendp1 + p2_addition
			if  new_best > best:
				best = new_best
				best_second = p2_addition
	print(best)
main()
```


p02637 AtCoder Grand Contest 046 - Permutation Cover

Given are an integer K and integers a_1,\dots, a_K. Determine whether a sequence P satisfying below exists. If it exists, find the lexicographically smallest such sequence.

* Every term in P is an integer between 1 and K (inclusive).
* For each i=1,\dots, K, P contains a_i occurrences of i.
* For each term in P, there is a contiguous subsequence of length K that contains that term and is a permutation of 1,\dots, K.

Constraints

* 1 \leq K \leq 100
* 1 \leq a_i \leq 1000 \quad (1\leq i\leq K)
* a_1 + \dots + a_K\leq 1000
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

K
a_1 a_2 \dots a_K

Output

If there is no sequence satisfying the conditions, print `-1`. Otherwise, print the lexicographically smallest sequence satisfying the conditions.

Examples

Input

3
2 4 3

Output

2 1 3 2 2 3 1 2 3

Input

4
3 2 3 2

Output

1 2 3 4 1 3 1 2 4 3

Input

5
3 1 4 1 5

Output

-1

```python
import sys

def find_permutation(aaa, use):
    """
    iの残り使用数がaaa[i-1]の状態で
    集合useにある文字群(1～k)を後ろに繋げる方法で
    それよりさらに後が破綻しないような繋げ方のうち
    辞書順最小のものを求める。

    ただし（この関数からは見えないが）現在確定済み配列の
    末尾 (k - |use|) 個は、useに含まれない要素が1回ずつ登場することを前提とする。
    （つまり、この関数の結果を繋げると、末尾 k 個が順列になる）

    どうやっても破綻する場合はNoneを返す。

    :param aaa:
    :param use:
    :return:
    """

    max_a = -1
    min_a = 1005
    max_fixed = -1

    for i in range(k):
        a = aaa[i]
        if i + 1 in use:
            min_a = min(min_a, a)
            max_a = max(max_a, a)
        else:
            max_fixed = max(max_fixed, a)

    if max(max_a, max_fixed + 1) > 2 * min_a:
        return None

    if max_a < 2 * min_a:
        return sorted(use)

    front = []
    rear = []
    either = []
    for i in use:
        if aaa[i - 1] == max_a:
            front.append(i)
        elif aaa[i - 1] == min_a:
            rear.append(i)
        else:
            either.append(i)

    max_front = front[-1]
    for i in either:
        if i < max_front:
            front.append(i)
        else:
            rear.append(i)
    front.sort()
    rear.sort()
    front.extend(rear)

    return front

def solve(k, aaa):
    if k == 1:
        return [1] * aaa[0]

    min_a = min(aaa)
    max_a = max(aaa)
    if min_a * 2 < max_a:
        return [-1]

    ans = []
    ans.extend(find_permutation(aaa, set(range(1, k + 1))))
    for i in range(k):
        aaa[i] -= 1

    remaining = sum(aaa)
    while remaining:
        use = set(range(1, k + 1))
        candidates = []
        for r in range(k):
            result = find_permutation(aaa, use)
            if result is not None:
                candidates.append(result)

            use.remove(ans[-r - 1])
        adopted = min(candidates)
        ans.extend(adopted)
        for i in adopted:
            aaa[i - 1] -= 1
        remaining -= len(adopted)

    return ans

k, *aaa = map(int, sys.stdin.buffer.read().split())
print(*solve(k, aaa))

```


p02768 AtCoder Beginner Contest 156 - Bouquet

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

* All values in input are integers.
* 2 \leq n \leq 10^9
* 1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print `0`.)

Examples

Input

4 1 3

Output

7

Input

1000000000 141421 173205

Output

34076506

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

mod = 10 ** 9 + 7
k = max(a,b)
com = [1]

for i in range(1,k+1):
    com.append((com[i-1]*(n-i+1)*pow(i,mod-2,mod))%mod)

print((pow(2,n,mod)-1-com[a]-com[b])%mod)
```


p02903 AtCoder Grand Contest 038 - 01 Matrix

We have a square grid with H rows and W columns. Snuke wants to write 0 or 1 in each of the squares. Here, all of the following conditions have to be satisfied:

* For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)
* For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

* 1 \leq H,W \leq 1000
* 0 \leq A
* 2 \times A \leq W
* 0 \leq B
* 2 \times B \leq H
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

s_{11}s_{12}\cdots s_{1W}
s_{21}s_{22}\cdots s_{2W}
\vdots
s_{H1}s_{H2}\cdots s_{HW}

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Examples

Input

3 3 1 1

Output

100
010
001

Input

1 5 2 0

Output

01010

```python
H,W,A,B = map(int,input().split())
for i in range(B):
  print("0"*A+"1"*(W-A))
for j in range(H-B):
  print("1"*A+"0"*(W-A))

```


p03038 AtCoder Beginner Contest 127 - Integer Cards

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq M \leq 10^5
* 1 \leq A_i, C_i \leq 10^9
* 1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Examples

Input

3 2
5 1 4
2 3
1 5

Output

14

Input

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Output

338

Input

3 2
100 100 100
3 99
3 99

Output

300

Input

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Output

10000000001

```python
N,M=map(int,input().split())
L=[(1,a) for a in map(int,input().split())]
for _ in range(M):
  L.append(tuple(map(int,input().split())))
L=sorted(L,key=lambda x: x[1],reverse=True)
ans,k=0,0
for n,a in L:
  if n+k>=N:
    ans+=a*(N-k)
    break
  else:
    ans+=a*n
    k+=n
print(ans)
```


p03179 Educational DP Contest - Permutation

Let N be a positive integer. You are given a string s of length N - 1, consisting of `<` and `>`.

Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7:

* For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is `<`, and p_i > p_{i + 1} if the i-th character in s is `>`.

Constraints

* N is an integer.
* 2 \leq N \leq 3000
* s is a string of length N - 1.
* s consists of `<` and `>`.

Input

Input is given from Standard Input in the following format:

N
s

Output

Print the number of permutations that satisfy the condition, modulo 10^9 + 7.

Examples

Input

4
<><

Output

5

Input

5
<<<<

Output

1

Input

20
>>>><>>><>><>>><<>>

Output

217136290


p03327 AtCoder Beginner Contest 099 - ABD

Decades have passed since the beginning of AtCoder Beginner Contest.

The contests are labeled as `ABC001`, `ABC002`, ... from the first round, but after the 999-th round `ABC999`, a problem occurred: how the future rounds should be labeled?

In the end, the labels for the rounds from the 1000-th to the 1998-th are decided: `ABD001`, `ABD002`, ..., `ABD999`.

You are given an integer N between 1 and 1998 (inclusive). Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Constraints

* 1 \leq N \leq 1998
* N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Examples

Input

999

Output

ABC

Input

1000

Output

ABD

Input

1481

Output

ABD


p03483 AtCoder Regular Contest 088 - Papple Sort

You are given a string S consisting of lowercase English letters. Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations.

Constraints

* 1 \leq |S| \leq 2 × 10^5
* S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If we cannot turn S into a palindrome, print `-1`. Otherwise, print the minimum required number of operations.

Examples

Input

eel

Output

1

Input

ataatmma

Output

4

Input

snuke

Output

-1

```python
from string import ascii_lowercase

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

def solve(s):
    indices = {c: [] for c in ascii_lowercase}
    for i, c in enumerate(s):
        indices[c].append(i)

    n = len(s)
    center = n // 2
    bubbles = [-1] * n
    odd_flag = False
    pairs = []
    for c, ids in indices.items():
        cnt = len(ids)
        if cnt & 1:
            if odd_flag:
                return -1
            odd_flag = True
            bubbles[ids[cnt // 2]] = center + 1
        for i in range(cnt // 2):
            li, ri = ids[i], ids[-i - 1]
            pairs.append((li, ri))
    pairs.sort()
    for i, (li, ri) in enumerate(pairs):
        bubbles[li] = i + 1
        bubbles[ri] = n - i

    ans = 0
    bit = Bit(n)
    for i, m in enumerate(bubbles):
        ans += i - bit.sum(m)
        bit.add(m, 1)
    return ans

print(solve(input()))

```


p03648 AtCoder Regular Contest 079 - Decrease (Contestant ver.)

We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller.

* Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by N, and increase each of the other elements by 1.

It can be proved that the largest element in the sequence becomes N-1 or smaller after a finite number of operations.

You are given an integer K. Find an integer sequence a_i such that the number of times we will perform the above operation is exactly K. It can be shown that there is always such a sequence under the constraints on input and output in this problem.

Constraints

* 0 ≤ K ≤ 50 \times 10^{16}

Input

Input is given from Standard Input in the following format:

K

Output

Print a solution in the following format:

N
a_1 a_2 ... a_N

Here, 2 ≤ N ≤ 50 and 0 ≤ a_i ≤ 10^{16} + 1000 must hold.

Examples

Input

0

Output

4
3 3 3 3

Input

1

Output

3
1 0 3

Input

2

Output

2
2 2

Input

3

Output

7
27 0 0 0 0 0 0

Input

1234567894848

Output

10
1000 193 256 777 0 1 1192 1234567891011 48 425

```python
k = int(input())
d, m = divmod(k, 50)
b = 49 + d
print(50)
print(*map(str, [b + 1] * m + [b - m] * (50 - m)))

```


p03804 AtCoder Beginner Contest 054 - Template Matching

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.
A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.
Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: `.` corresponds to a white pixel, and `#` corresponds to a black pixel.
The image A is given as N strings A_1,...,A_N.
The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).
Similarly, the template image B is given as M strings B_1,...,B_M.
The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

* 1≦M≦N≦50
* A_i is a string of length N consisting of `#` and `.`.
* B_i is a string of length M consisting of `#` and `.`.

Input

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

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print `Yes` if the template image B is contained in the image A. Print `No` otherwise.

Examples

Input

3 2
#.#
.#.
#.#
#.
.#

Output

Yes

Input

3 2
.#
.#.
.#
.
.#

Output

Yes

Input

4 1
....
....
....
....

Output

No

```python
m,n = [int(x) for x in input().split()]
a = []
b = []
for _ in range(m):
  a.append(input())
m = 0
for i in range(n):
  b.append(input())
  if b[i] in a[i]:
    m += 1
print('Yes') if m == n else print('No')

```


p03972 CODE FESTIVAL 2016 qual B - Gr-idian MST

On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.

There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.

The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.

Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.

Constraints

* 1 ≦ W,H ≦ 10^5
* 1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)
* 1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)
* p_i (0 ≦ i ≦ W−1) is an integer.
* q_j (0 ≦ j ≦ H−1) is an integer.

Input

Inputs are provided from Standard Input in the following form.

W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}

Output

Output an integer representing the minimum total cost.

Examples

Input

2 2
3
5
2
7

Output

29

Input

4 3
2
4
8
1
2
9
3

Output

60

```python
#!/usr/bin/env python3
import sys
try: from typing import Any, Union, List, Tuple, Dict
except ImportError: pass
sys.setrecursionlimit(10**6)
def debug(*args): print(*args, file=sys.stderr)
def exit(): sys.exit(0)

W, H = map(int, input().split())
p = []
for i in range(W):
    p.append(int(input()))
q = []
for j in range(H):
    q.append(int(input()))

a = []
for i in range(W):
    a.append(("p", i, p[i]))
for j in range(H):
    a.append(("q", j, q[j]))

a.sort(key=lambda x: x[2])

p_used = 0
q_used = 0
count = 0
cost = 0
i = 0
while True:
    now = a[i]
    if now[0] == "p":
        now_count = H+1 - q_used
        if count + now_count > (W+1)*(H+1) - 1:
            now_count = (W+1)*(H+1) - 1 - count
        count += now_count
        cost += now[2] * now_count
        p_used += 1
    else:
        now_count = W+1 - p_used
        if count + now_count > (W+1)*(H+1) - 1:
            now_count = (W+1)*(H+1) - 1 - count
        count += now_count
        cost += now[2] * now_count
        q_used += 1
    if count == (W+1)*(H+1) - 1:
        break
    i += 1
debug(count)
print(cost)

```


p00061 Rank Checker

The time is 2020. There is data that saves the qualifying results of PC Koshien 2020. This data stores the reference number and the number of correct answers assigned to each team. Here, the ranking is determined by the number of correct answers, and the ranking is given in descending order of the number of correct answers, such as 1st, 2nd, and so on.

Enter the qualifying result data and reference number from the keyboard, and create a program that outputs the ranking of the team with that number.

Note

In the data of the input example, if the teams are arranged in order of the number of correct answers:

3,30
1,20
2,20
6,20
4,10
5,10

It will be. Here, in order to determine the ranking based on the number of correct answers, the 30-question correct answer team is ranked 1st, the 20-question correct answer team is ranked 2nd, and the 10-question correct answer team is ranked 3rd. Please note that this is different from the usual ranking with the correct team in 5th place).

Input

The input data consists of two parts. The first half is the qualifying result data, and the second half is the inquiry of the team number for which you want to know the ranking. The format of the qualifying result data is as follows.

p1, s1
p2, s2
...
...
0,0

pi (1 ≤ pi ≤ 100) and si (0 ≤ si ≤ 30) are integers representing the reference number and the number of correct answers for the i-th team, respectively. It is assumed that the input of this data is completed when both the reference number and the number of correct answers are 0.

Then multiple inquiries in the second half are given. The inquiry format is as follows.

q1
q2
::

Each query is given the reference number qi (1 ≤ qi ≤ 30) on one line. Please process this until the end of the input. The number of inquiries does not exceed 100.

Output

For each inquiry, print the team ranking on one line.

Example

Input

1,20
2,20
3,30
4,10
5,10
6,20
0,0
1
2
4
5

Output

2
2
3
3

```python
def get_input():
    while True:
        try:
            yield ''.join(input())
        except EOFError:
            break

teams = [0 for i in range(101)]
points = [False for i in range(31)]
while True:
    a,b = [int(i) for i in input().split(",")]
    if a == 0 and b == 0:
        break

    teams[a] = b
    points[b] = True

N = list(get_input())
for l in range(len(N)):
    q = int(N[l])
    p = teams[q]
    ans = 0
    for i in range(30,-1,-1):
        if points[i]:
            ans += 1
        if i == p:
            break
    print(ans)

```


p00192 Multistory Parking Lot

There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking device allows one to be placed on an elevating pallet (a flat iron plate on which a car is placed) and parked in the upper tier, and the other to be parked in the lower tier.

In a parking lot that uses such a two-stage parking device, it is necessary to take out the car parked in the lower tier and dismiss it each time to put in and out the car in the upper tier, so be sure to manage it. Keeps the key to the parked car and puts it in and out as needed.

| <image>
--- | ---

Tsuruga Parking Lot is also one of the parking lots equipped with such a two-stage parking device, but due to lack of manpower, the person who cannot drive the car has become the manager. Therefore, once the car was parked, it could not be moved until the customer returned, and the car in the upper tier could not be put out until the owner of the car in the lower tier returned.

Create a program that meets the rules of the Tsuruga parking lot to help the caretaker who has to handle the cars that come to park one after another.

Tsuruga parking lot facilities

* There is one or more parking spaces, all equipped with a two-stage parking device.
* Each parking space is numbered starting from 1.
* Initially, it is assumed that no car is parked in the parking lot.

Tsuruga parking lot adopts the following rules.

When to stop the car

* The caretaker will be informed of the parking time of the car to be parked.
* We will park first in the parking space where no car is parked.
* If there is no parking space where no car is parked, park in an empty parking space. However, if there are multiple such parking spaces, follow the procedure below to park.
1. If the remaining parking time of a parked car is longer than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
2. If the remaining parking time of any parked car is less than the parking time of the car you are trying to park, park in the parking space with the smallest difference.
* If the car is full (no parking space available), the car you are trying to park will wait in turn until the parking space is available. As soon as it becomes available, we will park in order from the first car we were waiting for.

* Under each condition, if there are multiple applicable parking spaces, the parking space number will be the smallest. In addition, if there are cars leaving at the same time, parking will start after all the cars leaving at the same time, and as long as there are cars waiting, the cars that can be parked will be parked at the same time.

When the car leaves

* Cars that have passed the parking time notified by the manager will be shipped.
* If there are cars in multiple parking spaces that have passed the parking time at the same time, the car with the smallest parking space number will be shipped first.
* If the parking time of the car parked in the upper row has expired, you will have to wait until the car in the lower row leaves the garage. The upper car will be delivered at the same time after the lower car is delivered.

The figure below shows an example of how to park at Tsuruga Parking Lot. In this example, the number of parking spaces is 3, and cars B to E are already parked. Consider that car A, which has a parking time of 70 minutes, arrives there. You cannot park because two cars are already parked in parking space 3, and you will have to park in either parking space 1 or parking space 2 that is still vacant. Car B parked in parking space 1 has 50 minutes remaining and car C parked in parking space 2 has 22 minutes remaining, both of which are less than car A's parking time, so car A's parking Park in parking space 1 where car B, which has a smaller time difference, is parked. As a result, car B, which was parked earlier, will be in the upper row.

<image>

Create a program that inputs the number of parking spaces m, the number of cars parked n, and the parking time t of each car, and outputs the car reference numbers in the order in which they come out of the parking lot. However, cars are assigned an integer reference number starting with 1 in the order of input, and cars will come to park one by one every 10 minutes in the order of the reference number.

Input

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

m n
t1
t2
::
tn

The first line gives the number of two-stage parking devices m (1 ≤ m ≤ 10) and the number of cars parked n (1 ≤ n ≤ 100). The next n lines are given the parking time ti (1 ≤ ti ≤ 120) for the i-th car.

The number of datasets does not exceed 20.

Output

The reference number of the car is output to one line in the order of coming out of the parking lot for each data set. Please output the reference numbers separated by blanks.

Example

Input

3 5
90
52
82
84
70
2 4
10
30
40
60
0 0

Output

2 5 1 4 3
1 2 4 3

```python
from collections import deque

def out(time, parking):
  x = len(parking)
  outs = []
  for i in range(x):
    for j in range(2):
      if parking[i][j] != None:
        parking[i][j][0] -= time

  for i in range(x):
    c1 = parking[i][0]
    c2 = parking[i][1]
    if c1 != None and c2 != None:
      if c1[0] <= 0 and c2[0] <= 0:
        outs.append([c2[1], c1[1]])
        parking[i][0] = None
        parking[i][1] = None
      elif c2[0] <= 0:
        outs.append([c2[1]])
        parking[i][1] = None
    elif c1 != None:
      if c1[0] <= 0:
        outs.append([c1[1]])
        parking[i][0] = None
    elif c2 != None:
      if c2[0] <= 0:
        outs.append([c2[1]])
        parking[i][1] = None
  lst = []
  for l in outs:
    lst += l
  return lst

def into(num, time, parking):
  x = len(parking)
  times = []
  for i in range(x):
    if parking[i] == [None, None]:
      parking[i][0] = [time, num]
      return
    if parking[i][0] == None:
      times.append((parking[i][1][0], i))
    elif parking[i][1] == None:
      times.append((parking[i][0][0], i))
  times.sort()

  for t, ind in times:
    if t >= time:
      if parking[ind][0] == None:
        parking[ind][0] = [time, num]
      else:
        parking[ind][1] = [time, num]
      return
  else:
    max_t = t

  for t, ind in times:
    if t == max_t:
      if parking[ind][0] == None:
        parking[ind][0] = [time, num]
      else:
        parking[ind][1] = [time, num]
      return

while True:
  m, n = map(int, input().split())
  if m == 0:
    break

  parking = [[None] * 2 for _ in range(m)]
  wait = deque()
  space = m * 2
  ans = []

  for t in range(120 * n):
    o = out(1, parking)
    if o:
      space += len(o)
      ans += o

    if t % 10 == 0 and t <= 10 * (n - 1):
      time = int(input())
      wait.append((t // 10 + 1, time))

    for i in range(min(space, len(wait))):
      num, time = wait.popleft()
      into(num, time, parking)
      space -= 1
  print(*ans)

```


p00347 Forecast of Forces

Nobuo-kun and Shizuo-kun are playing a game of competing for territories on a rectangular island. As shown in Fig. 1 below, the entire island is made up of square compartments divided in a grid pattern, and the profits and losses resulting from these are indicated by integers.

<image>

In this game, move one piece to determine the boundaries of the territory. At the beginning of the game, the piece is at the northwestern end of the island (Fig. ①). The trajectory of the piece when moving this piece to the southeastern end of the island becomes the boundary of the territory. The two players move the pieces alternately. Pieces can only be moved to the grid point next to the south or the grid point next to the east (Fig. 2). When the piece reaches the edge of the island, move it in the south or east direction. The game is over when the piece reaches the southeastern end.

The area on the northeast side of the boundary after the game is the area of the first player, and the area on the southwest side is the area of the second player (Fig. ③). The sum of the profits and losses generated from the parcels contained within each player's territory is that player's core. Both of them are quite accustomed to the game and move the pieces accurately so that the value obtained by subtracting the opponent's score from their own score is the largest in the end.

Create a program that calculates the outcome at the end of the game given the size of the island and the gains and losses that result from each parcel. The result is the absolute value of the difference between the scores of Nobuo-kun and Shizuo-kun.

Input

The input is given in the following format.

W H
s1,1 s1,2 ... s1, W
s2,1 s2,2 ... s2, W
::
sH, 1 sH, 2 ... sH, W

The first line gives the number of east-west and north-south sections contained in the island W, H (1 ≤ W, H ≤ 1000). The following row H is given the gains and losses si, j (-1000 ≤ si, j ≤ 1000) that arise from the compartments in row i and column j. However, the direction in which the value of i increases is south, and the direction in which the value of j increases is east.

Output

The absolute value of the difference between the scores of Nobuo-kun and Shizuo-kun is output in one line.

Examples

Input

2 1
-2 1

Output

1

Input

2 2
2 -3
3 -1

Output

3

Input

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

Output

5

```python
import sys
sys.setrecursionlimit(10**7)
w, h = map(int, input().split())
S = [list(map(int, input().split())) for i in range(h)]
SW = [[0]*w for i in range(h)]
SH = [[0]*w for i in range(h)]
for i in range(h):
    cnt = 0
    for j in range(w-1, -1, -1):
        cnt += S[i][j]
        SW[i][j] = cnt
for j in range(w):
    cnt = 0
    for i in range(h-1, -1, -1):
        cnt += S[i][j]
        SH[i][j] = cnt
memo = {}
def dfs(x, y):
    if (x, y) in memo:
        return memo[x, y]
    if x == w or y == h:
        return 0
    if (x+y) % 2 == 0:
        # first
        res = max(dfs(x+1, y) - SH[y][x], dfs(x, y+1) + SW[y][x])
    else:
        # second
        res = min(dfs(x+1, y) - SH[y][x], dfs(x, y+1) + SW[y][x])
    memo[x, y] = res
    return res
print(abs(dfs(0, 0)))
```


p00543 Swapping Bibs

problem

N students from JOI High School are lined up in a row from east to west. The i-th student from the western end of the column is student i. Each student has a bib with one integer. Initially, the integer Ai is written on the number of student i.

There are M batons, and the batons are numbered from 1 to M. For k = 1, 2, ..., M, perform the following operations. The operation related to baton k (2 ≤ k ≤ M) is performed after the operation related to baton k -1 is completed.

1. The teacher gives the baton k to student 1.
2. Students who receive the baton pass the baton according to the following rules.
* Rule: Suppose student i receives the baton k.
* 1 ≤ i ≤ N-1: When the remainder of the integer of the number of student i divided by k is greater than the remainder of the integer of the number of student i + 1 divided by k, student i and student i + 1 exchanges the number, and student i passes the baton to student i + 1. Otherwise, student i passes the baton to student i + 1 without changing the bib.
* When i = N: Student N passes the baton to the teacher.
3. When the teacher receives the baton k from student N, the operation related to the baton k is finished.

Given the integer and the number of batons M that were originally written in the student number, write a program to find the integer of each student's number after the teacher receives the baton M from student N.

input

The input consists of 1 + N lines.

The integers N and M (1 ≤ N ≤ 100, 1 ≤ M ≤ 100) are written on the first line, separated by blanks, and represent the number of students and the number of batons, respectively.

The integer Ai (1 ≤ Ai ≤ 1000) is written on the i-th line (1 ≤ i ≤ N) of the following N lines, and represents the integer Ai first written on the number of student i.

output

The output consists of N lines. On line i (1 ≤ i ≤ N), output the integer of the number of student i after the teacher receives the baton M from student N.

Input / output example

Input example 1

6 4
3
2
8
3
1
Five

Output example 1

2
3
1
8
Five
3

Input example 2

10 6
1
2
3
Four
Five
6
7
8
9
Ten

Output example 2

6
1
2
3
Ten
Four
8
7
9
Five

Input / output example 1 has 6 students. Initially, the student numbers are 3, 2, 8, 3, 1, and 5, in that order. There are four batons.

* At the end of the operation related to baton 1, the student numbers are 3, 2, 8, 3, 1, and 5, respectively.
* At the end of the operation related to baton 2, the student numbers are 2, 8, 3, 3, 1, and 5, respectively.
* At the end of the operation related to baton 3, the student numbers are 2, 3, 3, 1, 8, and 5, respectively.
* At the end of the operation related to baton 4, the student numbers are 2, 3, 1, 8, 5, and 3 in order.

Creative Commons License

Information Olympics Japan Committee work "15th Japan Information Olympics JOI 2015/2016 Qualifying Competition Tasks"

Example

Input

6 4
3
2
8
3
1
5

Output

2
3
1
8
5
3

```python
n,m=map(int,input().split())
a=[int(input()) for _ in range(n)]
for i in range(1,m+1):
    for j in range(n-1):
        if a[j]%i>a[j+1]%i:a[j],a[j+1]=a[j+1],a[j]
for i in a:print(i)
```


p00707 The Secret Number

Your job is to find out the secret number hidden in a matrix, each of whose element is a digit ('0'-'9') or a letter ('A'-'Z'). You can see an example matrix in Figure 1.

<image>

Figure 1: A Matrix

The secret number and other non-secret ones are coded in a matrix as sequences of digits in a decimal format. You should only consider sequences of digits D1 D2 ... Dn such that Dk+1 (1 <= k < n) is either right next to or immediately below Dk in the matrix. The secret you are seeking is the largest number coded in this manner.

Four coded numbers in the matrix in Figure 1, i.e., 908820, 23140037, 23900037, and 9930, are depicted in Figure 2. As you may see, in general, two or more coded numbers may share a common subsequence. In this case, the secret number is 23900037, which is the largest among the set of all coded numbers in the matrix.

<image>

Figure 2: Coded Numbers

In contrast, the sequences illustrated in Figure 3 should be excluded: 908A2 includes a letter; the fifth digit of 23149930 is above the fourth; the third digit of 90037 is below right of the second.

<image>

Figure 3: Inappropriate Sequences

Write a program to figure out the secret number from a given matrix.

Input

The input consists of multiple data sets, each data set representing a matrix. The format of each data set is as follows.

> W H
>  C11C12 ... C1W
>  C21C22 ... C2W
>  ...
>  CH1CH2 ... CHW
>

In the first line of a data set, two positive integers W and H are given. W indicates the width (the number of columns) of the matrix, and H indicates the height (the number of rows) of the matrix. W+H is less than or equal to 70.

H lines follow the first line, each of which corresponds to a row of the matrix in top to bottom order. The i-th row consists of W characters Ci1Ci2 ... CiW in left to right order. You may assume that the matrix includes at least one non-zero digit.

Following the last data set, two zeros in a line indicate the end of the input.

Output

For each data set, print the secret number on a line. Leading zeros should be suppressed.

Example

Input

7 4
9R2A993
0E314A0
8A900DE
820R037
6 7
JH03HE
ID7722
0DA1AH
30C9G5
99971A
CA7EAI
AHLBEM
20 2
A1234567891234CBDEGH
BDEDF908034265091499
0 0

Output

23900037
771971
12345908034265091499

```python
from collections import defaultdict
def main(w, h):
    field = [list(input()) for i in range(h)]
    d = defaultdict(str)
    for y in range(h - 1, -1, -1):
        for x in range(w - 1, -1, -1):
            if "0" <= field[y][x] <= "9":
                d[(x, y)] = field[y][x]
    for y in range(h - 1, -1, -1):
        for x in range(w - 1, -1, -1):
            if "0" <= field[y][x] <= "9":
                if len(d[(x + 1, y)]) == len(d[(x, y + 1)]):
                    d[(x, y)] = field[y][x] + max(d[(x + 1, y)], d[(x, y + 1)])
                elif len(d[(x + 1, y)]) < len(d[(x, y + 1)]):
                    d[(x, y)] = field[y][x] + d[(x, y + 1)]
                else:
                    d[(x, y)] = field[y][x] + d[(x + 1, y)]
    ans = 0
    for v in d.values():
        if v == "":
            continue
        ans = max(ans, int(v))
    print(ans)

while 1:
    w, h = map(int, input().split())
    if h == w == 0:
        break
    main(w, h)

```


p01110 Origami

Origami, or the art of folding paper

Master Grus is a famous origami (paper folding) artist, who is enthusiastic about exploring the possibility of origami art. For future creation, he is now planning fundamental experiments to establish the general theory of origami.

One rectangular piece of paper is used in each of his experiments. He folds it horizontally and/or vertically several times and then punches through holes in the folded paper.

The following figure illustrates the folding process of a simple experiment, which corresponds to the third dataset of the Sample Input below. Folding the 10 × 8 rectangular piece of paper shown at top left three times results in the 6 × 6 square shape shown at bottom left. In the figure, dashed lines indicate the locations to fold the paper and round arrows indicate the directions of folding. Grid lines are shown as solid lines to tell the sizes of rectangular shapes and the exact locations of folding. Color densities represent the numbers of overlapping layers. Punching through holes at A and B in the folded paper makes nine holes in the paper, eight at A and another at B.

<image>

Your mission in this problem is to write a computer program to count the number of holes in the paper, given the information on a rectangular piece of paper and folding and punching instructions.

Input

The input consists of at most 1000 datasets, each in the following format.

> n m t p
>  d1 c1
>  ...
>  dt ct
>  x1 y1
>  ...
>  xp yp
>

n and m are the width and the height, respectively, of a rectangular piece of paper. They are positive integers at most 32. t and p are the numbers of folding and punching instructions, respectively. They are positive integers at most 20. The pair of di and ci gives the i-th folding instruction as follows:

* di is either 1 or 2.
* ci is a positive integer.
* If di is 1, the left-hand side of the vertical folding line that passes at ci right to the left boundary is folded onto the right-hand side.
* If di is 2, the lower side of the horizontal folding line that passes at ci above the lower boundary is folded onto the upper side.

After performing the first i−1 folding instructions, if di is 1, the width of the shape is greater than ci. Otherwise the height is greater than ci. (xi + 1/2, yi + 1/2) gives the coordinates of the point where the i-th punching instruction is performed. The origin (0, 0) is at the bottom left of the finally obtained shape. xi and yi are both non-negative integers and they are less than the width and the height, respectively, of the shape. You can assume that no two punching instructions punch holes at the same location.

The end of the input is indicated by a line containing four zeros.

Output

For each dataset, output p lines, the i-th of which contains the number of holes punched in the paper by the i-th punching instruction.

Sample Input

2 1 1 1
1 1
0 0
1 3 2 1
2 1
2 1
0 0
10 8 3 2
2 2
1 3
1 1
0 1
3 4
3 3 3 2
1 2
2 1
1 1
0 1
0 0
0 0 0 0

Output for the Sample Input

2
3
8
1
3
6

Example

Input

2 1 1 1
1 1
0 0
1 3 2 1
2 1
2 1
0 0
10 8 3 2
2 2
1 3
1 1
0 1
3 4
3 3 3 2
1 2
2 1
1 1
0 1
0 0
0 0 0 0

Output

2
3
8
1
3
6

```python
while(True):
    n,m,t,p=map(int,input().split())
    if (n,m,t,p)==(0,0,0,0):
        break
    d=[0 for  i in range(t)]
    c=[0 for  i in range(t)]
    x=[0 for  i in range(p)]
    y=[0 for  i in range(p)]
    nnow,mnow=n,m
    for i in range(t):
        d[i],c[i]=map(int,input().split())
    for i in range(p):
        x[i],y[i]=map(int,input().split())
    paper=[[1 for j in range(n)] for i in range(m)]
    for k in range(t):
        if d[k]==1:
            nnext=max(c[k],nnow-c[k])
            nextpaper=[[0 for j in range(nnext)] for i in range(mnow)]
            if c[k]<=nnow-c[k]:
                for i in range(mnow):
                    for j in range(nnow-c[k]):
                        nextpaper[i][j]+=paper[i][j+c[k]]
                    for j in range(c[k]):
                        nextpaper[i][j]+=paper[i][c[k]-j-1]
            else:
                for i in range(mnow):
                    for j in range(c[k]):
                        nextpaper[i][-j-1]+=paper[i][j]
                    for j in range(nnow-c[k]):
                        nextpaper[i][j]+=paper[i][j+c[k]]
            nnow=nnext
        else:
            mnext=max(c[k],mnow-c[k])
            nextpaper=[[0 for j in range(nnow)] for i in range(mnext)]
            if c[k]<=mnow-c[k]:
                for j in range(nnow):
                    for i in range(mnow-c[k]):
                        nextpaper[i][j]+=paper[i][j]
                    for i in range(c[k]):
                        nextpaper[-i-1][j]+=paper[i+mnow-c[k]][j]
            else:
                for j in range(nnow):
                    for i in range(mnow-c[k]):
                        nextpaper[-i-1][j]+=paper[mnow-c[k]-1-i][j]
                    for i in range(c[k]):
                        nextpaper[i][j]+=paper[-i-1][j]
            mnow=mnext
        paper=[[nextpaper[i][j] for j in range(nnow)] for i in range(mnow)]
    ans=0
    for i in range(p):
        print(paper[-y[i]-1][x[i]])

```


p01563 Connect

You are playing a solitaire puzzle called "Connect", which uses several letter tiles.

There are R × C empty cells. For each i (1 ≤ i ≤ R), you must put a string si (1 ≤ |si| ≤ C) in the i-th row of the table, without changing the letter order. In other words, you choose an integer sequence {aj} such that 1 ≤ a1 < a2 < ... < a|si| ≤ C , and put the j-th character of the string si in the aj-th column (1 ≤ j ≤ |si|).

For example, when C = 8 and si = "ICPC", you can put si like followings.

I_C_P_C_
ICPC____
_IC___PC

'_' represents an empty cell.

For each non-empty cell x, you get a point equal to the number of adjacent cells which have the same character as x. Two cells are adjacent if they share an edge.

Calculate the maximum total point you can get.

Input

The first line contains two integers R and C (1 ≤ R ≤ 128, 1 ≤ C ≤ 16).

Then R lines follow, each of which contains si (1 ≤ |si| ≤ C). All characters of si are uppercase letters.

Output

Output the maximum total point in a line.

Examples

Input

2 4
ACM
ICPC

Output

2

Input

2 9
PROBLEMF
CONNECT

Output

6

Input

4 16
INTERNATIONAL
COLLEGIATE
PROGRAMMING
CONTEST

Output

18

```python
# seishin.py
import sys
readline = sys.stdin.readline
write = sys.stdout.write

def gen(N, K):
    if K == 0:
        yield 0
        return
    v = (1 << K) - 1
    N2 = (1 << N)
    while v < N2:
        yield v
        x = v & -v; y = v + x
        v = ((v & ~y) // x >> 1) | y

def solve():
    R, C = map(int, readline().split())
    S = [readline().strip() for i in range(R)]
    C2 = (1 << C)
    bc = [0]*C2
    for state in range(1, C2):
        bc[state] = bc[state ^ (state & -state)] + 1

    LI = [None]*(C+1)
    RI = [None]*(C+1)
    for sl in range(C+1):
        r0 = [None]*(C+1)
        r1 = [None]*(C+1)
        for j in range(C+1):
            sr = sl - (C-j)
            e0 = []
            for k in range(max(sr, 0), min(sl, C)+1):
                e0.extend(gen(j, k))
            r0[j] = e0
            r1[j] = [state << (C-j) for state in e0]
        LI[sl] = r0
        RI[sl] = r1

    dp0 = [0]*C2; dp1 = [0]*C2
    zeros = [0]*C2
    s = S[0]; sl = len(s)
    for j in range(1, C):
        dp1[:] = zeros
        b0 = (1 << (j-1))
        b1 = (1 << j)
        for state in LI[sl][j]:
            ll = bc[state]
            dp1[state] = dp0[state]
            if ll < sl:
                if state & b0 and s[ll-1] == s[ll]:
                    dp1[state | b1] = dp0[state] + 2
                else:
                    dp1[state | b1] = dp0[state]
        dp0, dp1 = dp1, dp0
    for i in range(1, R):
        p = S[i-1]; pl = len(p)
        s = S[i]; sl = len(s)
        for j in range(C):
            dp1[:] = zeros
            b0 = (1 << (j-1)) if j else 0
            b1 = (1 << j)
            L0 = LI[sl][j]; R0 = RI[pl][C-j-1]
            for state1 in L0:
                ll = bc[state1]
                if ll < sl:
                    c = s[ll]
                    for state2 in R0:
                        rl = bc[state2]
                        state = state1 | state2
                        n_state = state | b1

                        if j < C-1:
                            dp1[state] = max(dp0[state], dp0[n_state]) if rl < pl else dp0[state]
                        r1 = max(dp0[state], (dp0[n_state] + 2 if (p[-rl-1] == c) else dp0[n_state])) if rl < pl else dp0[state]
                        if state & b0 and s[ll-1] == c:
                            dp1[n_state] = r1 + 2
                        else:
                            dp1[n_state] = r1
                else:
                    for state2 in R0:
                        state = state1 | state2
                        if bc[state2] < pl:
                            dp1[state] = max(dp0[state], dp0[state | b1])
                        else:
                            dp1[state] = dp0[state]
            dp0, dp1 = dp1, dp0
    write("%d\n" % max(dp0))
solve()

```


p01725 Unordered Operators

One day, Ikta, an elementary school student, received a piece of paper with mathematical formulas from his grandfather. Apparently, the grandfather will give you as much money as the answer to the formula. Ikta has only learned addition, subtraction, and multiplication, so only addition, subtraction, and multiplication are used in mathematical formulas. In normal calculation, multiplication must be calculated before addition and subtraction, but Ikta had a vague understanding of operator precedence, so for the time being, it is convenient to maximize the calculation result of the formula. I decided to consider a good priority.

Given the three binary operators + − × and a formula containing parentheses. Change the precedence of the three operators as you like and answer the calculation result when the formula is maximized.

However, note the following points.

* Operators are always left-associative. (Operators with the same precedence are always calculated from the left side of the formula.)
* Different operators may have the same precedence.
* Do not change the priority while calculating one formula.

Input

The input is given in the following format.
A formula consisting of numbers from 0 to 9 and the operators'+','-','*' and parentheses'(',')'

* To be precise, the input is in the format shown in BNF below.

> <expr> :: = (<expr>) | <number> | <expr> <op> <expr>
> <op> :: = + |-| *

<number> represents a non-negative integer.

Constraints

The input satisfies the following constraints.

* The formula is 200 characters or less.
* No matter what priority is set, it will not overflow as a result of calculation or in the middle of it as a 64-bit integer type.

Output

Output the maximum value obtained from the formula in one line.

Examples

Input

3-2*3

Output

3

Input

(5-3*4)*(0-2+1)

Output

21

Input

1-2+3-4+5-6*0

Output

3

Input

(1989967-3*1-211+4487)

Output

8511076028

```python
from sys import setrecursionlimit
setrecursionlimit(10 ** 8)

O = {'+': lambda l, r: l + r,
     '-': lambda l, r: l - r,
     '*': lambda l, r: l * r}

P = {'+': 0,
     '-': 0,
     '*': 0}

class Source():
    def __init__(self, S, i=0):
        self.S = S
        self.pos = i

def peek(S):
    return S.S[S.pos] if S.pos < len(S.S) else 'a'

def next(S):
    S.pos += 1

def expr(S, i):
    # print(S.pos)
    if i == 0:
        left = factor(S)
    else:
        left = expr(S, i - 1)

    while peek(S) in O and P[peek(S)] == i:
        ope = peek(S)
        next(S)
        if i == 0:
            right = factor(S)
        else:
            right = expr(S, i - 1)

        left = O[ope](left, right)

    # print(left, i)
    return left

def factor(S):
    if peek(S) == '(':
        next(S)
        res = expr(S, 2)
        next(S)
    else:
        res = num(S)
    return res

def num(S):
    sign = 1
    if peek(S) == '-':
        sign = -1
        next(S)
    res = 0
    while '0' <= peek(S) <= '9':
        res = res * 10 + int(peek(S))
        next(S)

    return sign * res

S = input()
ans = -int(1e19)

for plus in range(3):
    P['+'] = plus
    for minus in range(3):
        P['-'] = minus
        for times in range(3):
            P['*'] = times
            ans = max(ans, expr(Source(S), 2))

print(ans)

```


p01863 Miko Mi String

F: Miko Mi String-

story

Mikko Mikkomi ~! Everyone's idol, Miko Miko Tazawa! Today ~, with Mikoto ~, practice the string algorithm, let's do it ☆

Miko's special ~~ character making ~~ The slogan "MikoMikomi" becomes "MikoMikoMi" in Roman letters! In other words, if A = “Mi” and B = “Ko”, you can write in the form of ABABA! In this way, a character string that can be decomposed into the form of ABABA by properly determining A and B is called "Mikomi character string"! Miko is a popular person for everyone to become the name of a character string!

In order for everyone to use the Mikomi character string, I decided to make a program to judge whether the given character string is the Mikomi character string, but I can't write a program longer than Miko and FizzBuzz. !! So ~, for Miko ~, I want you to write a program that judges Mikomi character strings ☆

...... You said it's cold now! ??

problem

A character string S consisting of uppercase and lowercase letters is given. Here, if there are two non-empty strings A and B that can be written as S = ABABA, then S is said to be a "Mikomi string". At this time, uppercase and lowercase letters of the alphabet shall be distinguished as different characters. Create a program that determines whether a given string is a string.

Input format

The input consists of only one line including the character string S. It can be assumed that S satisfies the following conditions.

* 1 ≤ | S | ≤ 10 ^ 6. However, | S | represents the length of the character string S.
* S consists only of uppercase or lowercase alphabets.

Since the input may be very large, it is recommended to use a high-speed function to receive the input.

Output format

If S is a character string, output "Love AB!" For A and B that satisfy S = ABABA. However, if multiple pairs of A and B satisfy the condition, output the one with the smallest | AB |. If S is not a Mikomi string, output "mitomerarenaiWA".

Input example 1

NicoNicoNi

Output example 1

Love Nico!

Input example 2

Kashikoi Kawaii Elichika

Output example 2

mitomerarenaiWA

Input example 3

LiveLiveL

Output example 3

Love Live!

Input example 4

AizunyanPeroPero

Output example 4

mitomerarenaiWA

Input example 5

AAAAAAAAAAAAAA

Output example 5

Love AAAAA!

Example

Input

NicoNicoNi

Output

Love Nico!

```python
s = input()
length = len(s)
BASE = 100
MOD1 = 1000000007
MOD2 = 2147483647
acc1 = 0
acc2 = 0
hlst1 = [0]
hlst2 = [0]
for c in s:
  i = ord(c)
  acc1 = (acc1 * BASE + i) % MOD1
  acc2 = (acc2 * BASE + i) % MOD2
  hlst1.append(acc1)
  hlst2.append(acc2)

def calc_hash(left, right, xlen):
  return ((hlst1[right] - hlst1[left] * pow(BASE, xlen, MOD1)) % MOD1,
          (hlst2[right] - hlst2[left] * pow(BASE, xlen, MOD2)) % MOD2)

for i in range(length // 3, -1, -1):
  if (length - (i + 1) * 3) % 2:continue
  alen = i + 1
  blen = (length - (i + 1) * 3) // 2
  if blen <= 0:continue
  ha1 = calc_hash(0, alen, alen)
  ha2 = calc_hash(alen + blen, blen + alen * 2, alen)
  if ha1 != ha2:continue
  ha3 = calc_hash(blen * 2 + alen * 2, blen * 2 + alen * 3, alen)
  if ha1 != ha3:continue
  hb1 = calc_hash(alen, alen + blen, blen)
  hb2 = calc_hash(blen + alen * 2, blen * 2 + alen * 2, blen)
  if hb1 != hb2:continue
  print("Love {}!".format(s[:i + 1 + blen]))
  break
else:
  print("mitomerarenaiWA")

```


p01998 Prime Number

problem

One day, Sosusa, who loves prime numbers, was playing with the pair $ (p, q) $, where $ p + q $ is a prime number. Suddenly, Sosusa wondered how many of these pairs were prime numbers with $ p $ and $ q $ both less than or equal to $ N $. Find the number on your behalf.

output

Output the number of pairs. Also, output a line break at the end.

Example

Input

3

Output

2

```python
import math

N = int(input())
P = [True for x in range(N + 3)]

P[0] = False
P[1] = False

for i in range(2, int(math.sqrt(N + 3)) + 1):
    if P[i]:
        for j in range(i * 2, N + 3, i):
            P[j] = False

count = 0

for q in range(3, N + 1):
    if P[q] and P[2 + q]:
        count += 2

print(count)

```


p02285 Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

* insert  $k$: Insert a node containing $k$ as key into $T$.
* find $k$: Report whether $T$ has a node containing $k$.
* delete $k$: Delete a node containing $k$.
* print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

1. If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).
2. If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.
3. If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Constraints

* The number of operations $\leq 500,000$
* The number of print operations $\leq 10$.
* $-2,000,000,000 \leq key \leq 2,000,000,000$
* The height of the binary tree does not exceed 100 if you employ the above pseudo code.
* The keys in the binary search tree are all different.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key

Example

Input

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Output

yes
yes
yes
no
no
no
yes
yes
 1 2 3 7 8 22
 8 2 1 3 7 22
 1 2 8 22
 8 2 1 22

```python
class Node:
    def __init__(self,key,left=None,right=None,parent=None):
        self.key = key
        self.left = left
        self.right = right
        self.parent = parent

root=None

#前序排序
def PreorderTreeWalk(u):
    if u == None:
        return
    print(" %d"%u.key,end='')
    PreorderTreeWalk(u.left)
    PreorderTreeWalk(u.right)

#中序排序
def InorderTreeWalk(u):
    if (u == None):
        return
    InorderTreeWalk(u.left)
    print(" %d"%u.key,end='')
    InorderTreeWalk(u.right)

def insert(value):
    global root

    y = None
    x = root
    z = Node(value)

    # 从根结点往下遍历
    while (x != None) :
        y = x
        # z 比 x 小， 则从x的左侧遍历
        # z 比 x 大， 则从x的右侧遍历
        if (z.key < x.key):
            x = x.left
        else:
            x = x.right

    z.parent = y

    #没有父结点的是root
    if (y == None):
        root = z
    else:
        # z 比 y 小， 则在y的左侧
        # z 比 y 大， 则在y的右侧
        if (z.key < y.key):
            y.left = z
        else:
            y.right = z

def find(u,value):
    while (u != None and u.key != value):
        if (value < u.key):
            u = u.left;
        else:
            u = u.right;

    return u

# 树的最小值
def treeMinimum(x):
    while (x.left != None):
        x = x.left;
    return x

# case3如果同时具有左右子树。
#可以将结点x的左子树的最大值（也就是左子树一直往右孩子节点遍历即是最大值）
#或者右子树的最小值（也就是右子树一直往左孩子节点遍历即是最小值）替换x，然后拼接左子树或者右子树
#搜索后一个结点
def treeSuccessor(x) :
    if (x.right != None):
        return treeMinimum(x.right)

    y = x.parent;

    if x==y.left:
        return y
    else:
        while (y != None and x == y.right) :
            x = y
            x = y.parent

    return y

def treeDelete(z) :
        #x没有子结点，则将x结点删除即可
        #如果x只有左子树或者只有右子树，则将子树拼接上父结点即可
        # 确定要删除的结点
    if (z.left == None or z.right == None):
        y = z
    else:
        y = treeSuccessor(z)

    # 确定y的子结点x
    if (y.left != None):
        x = y.left
    else:
        x = y.right

    # 让子结点链接父结点
    if (x != None):
        x.parent = y.parent

    # 让父结点链接子结点
    if (y.parent == None):
        root = x
    else:
        if (y == y.parent.left):
            y.parent.left = x
        else:
            y.parent.right = x

    #case 3
    if (y != z):
        z.key = y.key;

n=int(input())
s=[]
for i in range(n):
    s=[x for x in input().split()]
    if s[0][0]=='i':
        insert(int(s[1]))
    elif s[0][0]=='f':
        f = find(root,int(s[1]));
        if (f != None):
            print("yes")
        else:
            print("no")
    elif s[0][0]=='d':
            treeDelete(find(root, int(s[1])));
    else:
        InorderTreeWalk(root)
        print()

        PreorderTreeWalk(root)
        print()

```


p02432 Deque

For a dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations:

* push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$.
* randomAccess($p$): Print element $a_p$.
* pop($d$): Delete the first element of $A$, if $d = 0$. Delete the last element of $A$, if $d = 1$.

$A$ is a 0-origin array and it is empty in the initial state.

Constraints

* $1 \leq q \leq 400,000$
* $0 \leq p < $ the size of $A$
* $-1,000,000,000 \leq x \leq 1,000,000,000$

Input

The input is given in the following format.

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

Each query $query_i$ is given by

0 $d$ $x$

or

1 $p$

or

2 $d$

where the first digits 0, 1 and 2 represent push, randomAccess and pop operations respectively.

randomAccess and pop operations will not be given for an empty array.

Output

For each randomAccess, print $a_p$ in a line.

Example

Input

11
0 0 1
0 0 2
0 1 3
1 0
1 1
1 2
2 0
2 1
0 0 4
1 0
1 1

Output

2
1
3
4
1

```python
from collections import deque
class shinajina():
    def push(A,que):
        if que[1]==0:
            A.appendleft(que[2])
        elif que[1]==1:
            A.append(que[2])
    def randomaccess(A,que):
        print(A[que[1]])
    def pop(A,que):
        if que[1]==0:
            A.popleft()
        elif que[1]==1:
            A.pop()

def main():
    q = int(input())
    A = deque()
    query = [list( map(int,input().split())) for i in range(q)]
    for que in query:
        if que[0]==0:
            shinajina.push(A,que)
        elif que[0]==1:
            shinajina.randomaccess(A,que)
        elif que[0]==2:
            shinajina.pop(A,que)

if __name__ == '__main__':
    main()

```


1003_F. Abbreviation

You are given a text consisting of n space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. w_i is the i-th word of text. All words consist only of lowercase Latin letters.

Let's denote a segment of words w[i..j] as a sequence of words w_i, w_{i + 1}, ..., w_j. Two segments of words w[i_1 .. j_1] and w[i_2 .. j_2] are considered equal if j_1 - i_1 = j_2 - i_2, j_1 ≥ i_1, j_2 ≥ i_2, and for every t ∈ [0, j_1 - i_1] w_{i_1 + t} = w_{i_2 + t}. For example, for the text "to be or not to be" the segments w[1..2] and w[5..6] are equal, they correspond to the words "to be".

An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words w[2..4] and w[6..8] with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words w[2..5] and w[6..9] with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c".

What is the minimum length of the text after at most one abbreviation?

Input

The first line of the input contains one integer n (1 ≤ n ≤ 300) — the number of words in the text.

The next line contains n space-separated words of the text w_1, w_2, ..., w_n. Each word consists only of lowercase Latin letters.

It is guaranteed that the length of text does not exceed 10^5.

Output

Print one integer — the minimum length of the text after at most one abbreviation.

Examples

Input

6
to be or not to be

Output

12

Input

10
a ab a a b ab a a b c

Output

13

Input

6
aa bb aa aa bb bb

Output

11

Note

In the first example you can obtain the text "TB or not TB".

In the second example you can obtain the text "a AAAB AAAB c".

In the third example you can obtain the text "AB aa AB bb".

```python
# import time
N = 303
eq = []
dp = []
for i in range(N):
    eq.append([False] * N)
for i in range(N):
    dp.append([0] * N)
n = int(input())
s = input()
# t = time.time()
allsum = len(s)
s = s.split()
for i in range(n):
    eq[i][i] = True
    for j in range(i):
        eq[i][j] = eq[j][i] = s[i] == s[j]
for i in range(n - 1, -1, -1):
    for j in range(n - 1, -1, -1):
        if eq[i][j]:
            if i < n - 1 and j < n - 1:
                dp[i][j] = dp[i + 1][j + 1] + 1
            else:
                dp[i][j] = 1
ans = allsum
for i in range(n):
    su = 0
    for j in range(1, n - i + 1):
        su += len(s[i + j - 1])
        cnt = 1
        pos = i + j
        while pos < n:
            if dp[i][pos] >= j:
                cnt += 1
                pos += j - 1
            pos += 1
        cur = allsum - su * cnt + cnt
        if cnt > 1 and ans > cur:
            # print(allsum, su, cnt, j)
            ans = cur
print(ans)
# print(time.time() - t)

```


1027_G. X-mouse in the Campus

The campus has m rooms numbered from 0 to m - 1. Also the x-mouse lives in the campus. The x-mouse is not just a mouse: each second x-mouse moves from room i to the room i ⋅ x mod{m} (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the x-mouse is unknown.

You are responsible to catch the x-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the x-mouse enters a trapped room, it immediately gets caught.

And the only observation you made is GCD (x, m) = 1.

Input

The only line contains two integers m and x (2 ≤ m ≤ 10^{14}, 1 ≤ x < m, GCD (x, m) = 1) — the number of rooms and the parameter of x-mouse.

Output

Print the only integer — minimum number of traps you need to install to catch the x-mouse.

Examples

Input

4 3

Output

3

Input

5 2

Output

2

Note

In the first example you can, for example, put traps in rooms 0, 2, 3. If the x-mouse starts in one of this rooms it will be caught immediately. If x-mouse starts in the 1-st rooms then it will move to the room 3, where it will be caught.

In the second example you can put one trap in room 0 and one trap in any other room since x-mouse will visit all rooms 1..m-1 if it will start in any of these rooms.

```python
from math import gcd
def powmod(a,b,m):
 a%=m
 r=1
 while b:
  if b&1:r=r*a%m
  a=a*a%m
  b>>=1
 return r

def f(n):
 r=[]
 if (n&1)==0:
  e=0
  while (n&1)==0:n>>=1;e+=1
  yield (2,e)
 p=3
 while n>1:
  if p*p>n:p=n
  if n%p:
   p+=2
   continue
  e=1;n//=p
  while n%p==0:n//=p;e+=1
  yield (p,e)
  p+=2
 return r
m,x=map(int,input().split())
p=2
r=[(1,1)]
for p,e in f(m):
 assert e>=1
 ord=p-1
 assert powmod(x,ord,p)==1
 for pi,ei in f(p-1):
  while ord % pi == 0 and powmod(x,ord//pi,p)==1: ord//=pi
 ords=[(1,1),(ord,p-1)]
 q=p
 for v in range(2,e+1):
  q*=p
  if powmod(x,ord,q)!=1:ord*=p
  assert powmod(x,ord,q)==1
  ords.append((ord,q//p*(p-1)))
 r=[(a//gcd(a,c)*c,b*d) for a,b in r for c,d in ords]
print(sum(y//x for x,y in r))
```


1046_F. Splitting money

After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.

These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet.

This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most x satoshi (1 bitcoin = 10^8 satoshi). She can create new public address wallets for free and is willing to pay f fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal.

Input

First line contains number N (1 ≤ N ≤ 200 000) representing total number of public addresses Alice has.

Next line contains N integer numbers a_i (1 ≤ a_i ≤ 10^9) separated by a single space, representing how many satoshi Alice has in her public addresses.

Last line contains two numbers x, f (1 ≤ f < x ≤ 10^9) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction.

Output

Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal.

Example

Input

3
13 7 6
6 2

Output

4

Note

Alice can make two transactions in a following way:

0. 13 7 6 (initial state)

1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)

2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)

Since cost per transaction is 2 satoshies, total fee is 4.

```python
n = int(input())
a = list(map(int, input().split()))
max, fee = map(int, input().split())
total = 0
a.sort(reverse=True)
for i in range(n):
    if a[i]> max:
        num = -(-(a[i]-max)//(max+fee))
        total = total + fee*num
    else:
        break

print(total)

```


1070_E. Getting Deals Done

Polycarp has a lot of work to do. Recently he has learned a new time management rule: "if a task takes five minutes or less, do it immediately". Polycarp likes the new rule, however he is not sure that five minutes is the optimal value. He supposes that this value d should be chosen based on existing task list.

Polycarp has a list of n tasks to complete. The i-th task has difficulty p_i, i.e. it requires exactly p_i minutes to be done. Polycarp reads the tasks one by one from the first to the n-th. If a task difficulty is d or less, Polycarp starts the work on the task immediately. If a task difficulty is strictly greater than d, he will not do the task at all. It is not allowed to rearrange tasks in the list. Polycarp doesn't spend any time for reading a task or skipping it.

Polycarp has t minutes in total to complete maximum number of tasks. But he does not want to work all the time. He decides to make a break after each group of m consecutive tasks he was working on. The break should take the same amount of time as it was spent in total on completion of these m tasks.

For example, if n=7, p=[3, 1, 4, 1, 5, 9, 2], d=3 and m=2 Polycarp works by the following schedule:

  * Polycarp reads the first task, its difficulty is not greater than d (p_1=3 ≤ d=3) and works for 3 minutes (i.e. the minutes 1, 2, 3);
  * Polycarp reads the second task, its difficulty is not greater than d (p_2=1 ≤ d=3) and works for 1 minute (i.e. the minute 4);
  * Polycarp notices that he has finished m=2 tasks and takes a break for 3+1=4 minutes (i.e. on the minutes 5, 6, 7, 8);
  * Polycarp reads the third task, its difficulty is greater than d (p_3=4 > d=3) and skips it without spending any time;
  * Polycarp reads the fourth task, its difficulty is not greater than d (p_4=1 ≤ d=3) and works for 1 minute (i.e. the minute 9);
  * Polycarp reads the tasks 5 and 6, skips both of them (p_5>d and p_6>d);
  * Polycarp reads the 7-th task, its difficulty is not greater than d (p_7=2 ≤ d=3) and works for 2 minutes (i.e. the minutes 10, 11);
  * Polycarp notices that he has finished m=2 tasks and takes a break for 1+2=3 minutes (i.e. on the minutes 12, 13, 14).

Polycarp stops exactly after t minutes. If Polycarp started a task but has not finished it by that time, the task is not considered as completed. It is allowed to complete less than m tasks in the last group. Also Polycarp considers acceptable to have shorter break than needed after the last group of tasks or even not to have this break at all — his working day is over and he will have enough time to rest anyway.

Please help Polycarp to find such value d, which would allow him to complete maximum possible number of tasks in t minutes.

Input

The first line of the input contains single integer c (1 ≤ c ≤ 5 ⋅ 10^4) — number of test cases. Then description of c test cases follows. Solve test cases separately, test cases are completely independent and do not affect each other.

Each test case is described by two lines. The first of these lines contains three space-separated integers n, m and t (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5, 1 ≤ t ≤ 4 ⋅ 10^{10}) — the number of tasks in Polycarp's list, the number of tasks he can do without a break and the total amount of time Polycarp can work on tasks. The second line of the test case contains n space separated integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ 2 ⋅ 10^5) — difficulties of the tasks.

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

Output

Print c lines, each line should contain answer for the corresponding test case — the maximum possible number of tasks Polycarp can complete and the integer value d (1 ≤ d ≤ t) Polycarp should use in time management rule, separated by space. If there are several possible values d for a test case, output any of them.

Examples

Input

4
5 2 16
5 6 1 4 7
5 3 30
5 6 1 4 7
6 4 15
12 5 15 7 20 17
1 1 50
100

Output

3 5
4 7
2 10
0 25

Input

3
11 1 29
6 4 3 7 5 3 4 7 3 5 3
7 1 5
1 1 1 1 1 1 1
5 2 18
2 3 3 7 5

Output

4 3
3 1
4 5

Note

In the first test case of the first example n=5, m=2 and t=16. The sequence of difficulties is [5, 6, 1, 4, 7]. If Polycarp chooses d=5 then he will complete 3 tasks. Polycarp will work by the following schedule:

  * Polycarp reads the first task, its difficulty is not greater than d (p_1=5 ≤ d=5) and works for 5 minutes (i.e. the minutes 1, 2, ..., 5);
  * Polycarp reads the second task, its difficulty is greater than d (p_2=6 > d=5) and skips it without spending any time;
  * Polycarp reads the third task, its difficulty is not greater than d (p_3=1 ≤ d=5) and works for 1 minute (i.e. the minute 6);
  * Polycarp notices that he has finished m=2 tasks and takes a break for 5+1=6 minutes (i.e. on the minutes 7, 8, ..., 12);
  * Polycarp reads the fourth task, its difficulty is not greater than d (p_4=4 ≤ d=5) and works for 4 minutes (i.e. the minutes 13, 14, 15, 16);
  * Polycarp stops work because of t=16.

In total in the first test case Polycarp will complete 3 tasks for d=5. He can't choose other value for d to increase the number of completed tasks.

```python
import io, os
input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline

ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())

out = []
for _ in range(ii()):
    n, m, t = mi()
    p = li()

    def check(d):
        cur = tim = tot = totim = 0
        for i in range(n):
            x = p[i]
            if x > d: continue
            totim += x
            tim += x
            if totim > t: break
            cur += 1
            tot += 1
            if cur == m:
                totim += tim
                if totim > t: break
                cur = tim = 0
        return all(x > d for x in p[i+1:]), tot

    lo, hi = 1, t
    while lo < hi:
        mid = (lo + hi + 1) >> 1
        if check(mid)[0]:
            lo = mid
        else:
            hi = mid - 1

    if check(lo + 1)[1] > check(lo)[1]:
        lo += 1

    out.append('%d %d' % (check(lo)[1], lo))

print(*out, sep='\n')
```


1092_A. Uniform String

You are given two integers n and k.

Your task is to construct such a string s of length n that for each i from 1 to k there is at least one i-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.

You have to answer t independent queries.

Input

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

The next t lines are contain queries, one per line. The i-th line contains two integers n_i and k_i (1 ≤ n_i ≤ 100, 1 ≤ k_i ≤ min(n_i, 26)) — the length of the string in the i-th query and the number of characters in the i-th query.

Output

Print t lines. In the i-th line print the answer to the i-th query: any string s_i satisfying the conditions in the problem statement with constraints from the i-th query.

Example

Input

3
7 3
4 4
6 2

Output

cbcacab
abcd
baabab

Note

In the first example query the maximum possible minimal frequency is 2, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: "cbcabba", "ccbbaaa" (any permutation of given answers is also correct).

In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is 1).

In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is 3).

```python
t=int(input())
for _ in range(t):
	n,k=map(int,input().split())
	s=''
	for i in range(97,97+k):
		s+=chr(i)
	s=s*(n//k)+s[:n%k]
	print(s)

```


1140_D. Minimum Triangulation

You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.

Calculate the minimum weight among all triangulations of the polygon.

Input

The first line contains single integer n (3 ≤ n ≤ 500) — the number of vertices in the regular polygon.

Output

Print one integer — the minimum weight among all triangulations of the given polygon.

Examples

Input

3

Output

6

Input

4

Output

18

Note

According to Wiki: polygon triangulation is the decomposition of a polygonal area (simple polygon) P into a set of triangles, i. e., finding a set of triangles with pairwise non-intersecting interiors whose union is P.

In the first example the polygon is a triangle, so we don't need to cut it further, so the answer is 1 ⋅ 2 ⋅ 3 = 6.

In the second example the polygon is a rectangle, so it should be divided into two triangles. It's optimal to cut it using diagonal 1-3 so answer is 1 ⋅ 2 ⋅ 3 + 1 ⋅ 3 ⋅ 4 = 6 + 12 = 18.


1159_B. Expansion coefficient of the array

Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≤ i, j ≤ n the inequality k ⋅ |i - j| ≤ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists.

You are given an array of non-negative integers a_1, a_2, …, a_n. Find its expansion coefficient.

Input

The first line contains one positive integer n — the number of elements in the array a (2 ≤ n ≤ 300 000). The next line contains n non-negative integers a_1, a_2, …, a_n, separated by spaces (0 ≤ a_i ≤ 10^9).

Output

Print one non-negative integer — expansion coefficient of the array a_1, a_2, …, a_n.

Examples

Input

4
6 4 5 5

Output

1

Input

3
0 1 2

Output

0

Input

4
821 500 479 717

Output

239

Note

In the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| ≤ min(a_i, a_j), because all elements of the array satisfy a_i ≥ 3. On the other hand, this array isn't a 2-extension, because 6 = 2 ⋅ |1 - 4| ≤ min(a_1, a_4) = 5 is false.

In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension.

```python
from sys import stdin,stdout
a=int(stdin.readline())
z=list(map(int,stdin.readline().split()))
k=min(z);r=int(1e9);i=0;j=a-1
while i<=j:r=min(r,z[i]//max(i,a-i-1),z[j]//max(j,a-j-1));i+=1;j-=1
stdout.write(str(r))
```