1433_F. Zero Remainder Sum

You are given a matrix a of size n × m consisting of integers.

You can choose no more than \left⌊m/2\right⌋ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by k and this sum is the maximum.

In other words, you can choose no more than a half (rounded down) of elements in each row, you have to find the maximum sum of these elements divisible by k.

Note that you can choose zero elements (and the sum of such set is 0).

Input

The first line of the input contains three integers n, m and k (1 ≤ n, m, k ≤ 70) — the number of rows in the matrix, the number of columns in the matrix and the value of k. The next n lines contain m elements each, where the j-th element of the i-th row is a_{i, j} (1 ≤ a_{i, j} ≤ 70).

Output

Print one integer — the maximum sum divisible by k you can obtain.

Examples

Input

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

Output

24

Input

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

Output

56

Note

In the first example, the optimal answer is 2 and 4 in the first row, 5 and 2 in the second row and 7 and 4 in the third row. The total sum is 2 + 4 + 5 + 2 + 7 + 4 = 24.

```python
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write('\n'.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7

n,m,k=mdata()
A=[mdata() for i in range(n)]
dp1=[-INF]*k
dp1[0]=0
for i in range(n):
    dp=[[-INF]*(m//2+1) for _ in range(k)]
    dp[0][0]=0
    for j in range(m):
        a=A[i][j]
        for x in range(m // 2,0,-1):
            for y in range(k):
                dp[(y+a)%k][x]=max(dp[(y+a)%k][x],dp[y][x-1]+a)
    dp2=dp1[::]
    for x in range(k):
        for y in range(k):
            dp2[(x+y)%k]=max(dp2[(x+y)%k],dp1[x]+max(dp[y]))
    dp1=dp2[::]
out(dp1[0])
```


1458_E. Nim Shortcuts

After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap!

In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a player can take any positive number of stones from either one of the heaps. A player who is unable to move loses the game.

To make the game easier to playtest, you've introduced developer shortcuts. There are n shortcut positions (x_1, y_1), …, (x_n, y_n). These change the game as follows: suppose that before a player's turn the first and second heap contain x and y stones respectively. If the pair (x, y) is equal to one of the pairs (x_i, y_i), then the player about to move loses instantly, otherwise they are able to make moves as normal. Note that in the above explanation the two heaps and all pairs are ordered, that is, x must refer to the size of the first heap, and y must refer to the size of the second heap.

The game release was followed by too much celebration, and next thing you know is developer shortcuts made their way to the next official update of the game! Players now complain that the AI opponent has become unbeatable at certain stages of the game. You now have to write a program to figure out which of the given initial positions can be won by the starting player, assuming both players act optimally.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the number of shortcut positions, and the number of initial positions that need to be evaluated.

The following n lines describe shortcut positions. The i-th of these lines contains two integers x_i, y_i (0 ≤ x_i, y_i ≤ 10^9). It is guaranteed that all shortcut positions are distinct.

The following m lines describe initial positions. The i-th of these lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^9) — the number of stones in the first and second heap respectively. It is guaranteed that all initial positions are distinct. However, initial positions are not necessarily distinct from shortcut positions.

Output

For each initial position, on a separate line print "WIN" if the starting player is able to win from this position, and "LOSE" otherwise.

Example

Input

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

Output

LOSE
WIN
LOSE
WIN
LOSE

```python
from heapq import *
from bisect import bisect_left
n, m = map(int, input().split())

inf = 15 * 10 ** 8

norm = []
rev = []
slow = set()
for _ in range(n):x, y = map(int, input().split());heappush(norm, (x,y));heappush(rev, (y,x));slow.add((x,y))

cx = cy = 0

skipX=[]
skipY=[]

for i in range(2 * n):
    tl = tr = inf
    tlp = trp = (inf, inf)

    if norm:tl = norm[0][0] - cx;tlp = (norm[0][0] - cx, norm[0][1] - cy)

    if rev:tr = rev[0][0] - cy;trp = (rev[0][0] - cy, rev[0][1] - cx)

    if tlp < trp:
        x, y = heappop(norm)
        if tl < 0:continue
        cx+=tl;cy+=tl
        assert x == cx
        if y < cy:skipX.append(x);cx += 1
    else:
        y, x = heappop(rev)
        if tr < 0:
            continue
        cx+=tr;cy+=tr
        assert y == cy
        if x < cx:
            skipY.append(y)
            cy += 1

out = []
for _ in range(m):
    x, y = map(int, input().split())
    if (x, y) in slow:        out.append('LOSE');        continue
    csx = bisect_left(skipX, x);    csy = bisect_left(skipY, y)
    if csx < len(skipX) and skipX[csx] == x:        out.append('WIN');        continue
    if csy < len(skipY) and skipY[csy] == y:        out.append('WIN');        continue
    out.append('LOSE' if x-csx==y-csy else 'WIN')
print('\n'.join(map(str,out)))
```


1481_E. Sorting Books

One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first.

<image>

There are n books standing in a row on the shelf, the i-th book has color a_i.

You'd like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful if all books of the same color are next to each other.

In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.

What is the minimum number of operations you need to make the shelf beautiful?

Input

The first line contains one integer n (1 ≤ n ≤ 5 ⋅ 10^5) — the number of books.

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the book colors.

Output

Output the minimum number of operations to make the shelf beautiful.

Examples

Input

5
1 2 2 1 3

Output

2

Input

5
1 2 2 1 1

Output

1

Note

In the first example, we have the bookshelf [1, 2, 2, 1, 3] and can, for example:

  1. take a book on position 4 and move to the right end: we'll get [1, 2, 2, 3, 1];
  2. take a book on position 1 and move to the right end: we'll get [2, 2, 3, 1, 1].

In the second example, we can move the first book to the end of the bookshelf and get [2,2,1,1,1].

```python
n = int(input())
a = [int(x) - 1 for x in input().split()]
l = [-1 for _ in range(n + 1)]
r = [-1 for _ in range(n + 1)]
freq = [0 for _ in range(n + 1)]
dp = [0 for _ in range(n + 1)]
for i in range(n):
    if(l[a[i]] == -1): l[a[i]] = i
    r[a[i]] = i
for i in range(n - 1, -1, -1):
    dp[i] = dp[i + 1]
    freq[a[i]] += 1
    if (i == l[a[i]]):
        dp[i] = max(dp[i], dp[r[a[i]] + 1] + freq[a[i]])
    else :
        dp[i] = max(dp[i], freq[a[i]])
print(n - dp[0])

```


181_E. Playing with Superglue

Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.

We'll describe the rules of the game in more detail.

The players move in turns. The first player begins.

With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.

At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.

If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible — he can always spread the glue on the square from which the first player has just moved the chip.

We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.

You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.

Input

The first line contains six integers n, m, x1, y1, x2, y2 — the board sizes and the coordinates of the first and second chips, correspondingly (1 ≤ n, m ≤ 100; 2 ≤ n × m; 1 ≤ x1, x2 ≤ n; 1 ≤ y1, y2 ≤ m). The numbers in the line are separated by single spaces.

It is guaranteed that the chips are located in different squares.

Output

If the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.

Examples

Input

1 6 1 2 1 6

Output

First

Input

6 5 4 3 2 1

Output

First

Input

10 10 1 1 10 10

Output

Second

```python
n,m,x1,y1,x2,y2 = map(int, input().split())
n = abs(x1 - x2)
m = abs(y1 - y2)
if n > 4 or m > 4:
    print("Second")
elif n <= 3 and m <= 3:
    print("First")
elif min(n, m) <= 2:
    print("First")
else:
    print("Second")
```


205_B. Little Elephant and Sorting

The Little Elephant loves sortings.

He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ≤ r.

Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1 ≤ i < n) ai ≤ ai + 1 holds.

Input

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of array a. The next line contains n integers, separated by single spaces — array a (1 ≤ ai ≤ 109). The array elements are listed in the line in the order of their index's increasing.

Output

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

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

Examples

Input

3
1 2 3

Output

0

Input

3
3 2 1

Output

2

Input

4
7 4 1 47

Output

6

Note

In the first sample the array is already sorted in the non-decreasing order, so the answer is 0.

In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).

In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].

```python
def solve(arr, n):
    inc = 0
    ans = 0
    for i in range(1, n):
        arr[i] += inc
        if arr[i] >= arr[i - 1]:
            continue
        diff = arr[i - 1] - arr[i]
        ans += diff
        inc += diff
        arr[i] += diff
    # print(arr)
    # print(ans)
    return ans

def read():
    n = int(input())
    arr = list(map(int, input().strip().split()))
    ans = solve(arr, n)
    print(ans)

read()
```


22_A. Second Order Statistics

Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.

Input

The first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.

Output

If the given sequence has the second order statistics, output this order statistics, otherwise output NO.

Examples

Input

4
1 2 2 -4

Output

1

Input

5
1 2 3 1 1

Output

2

```python
n=int(input())
ar=[int(i) for i in input().split()]
ar=list(set(sorted(ar)))
ar.sort()

try:
	print(ar[1])
except IndexError:
	print("NO")
```


254_A. Cards with Numbers

Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.

Input

The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces.

Output

If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs.

Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.

Examples

Input

3
20 30 10 30 20 10

Output

4 2
1 5
6 3

Input

1
1 2

Output

-1

```python
from sys import stdin, stdout
import math,sys
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict,Counter
from os import path
import bisect as bi
import heapq
mod=10**9+7
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def inp():return (int(input()))
    def minp():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def inp():return (int(stdin.readline()))
    def minp():return(map(int,stdin.readline().split()))
####### ---- Start Your Program From Here ---- #######
n=inp()
a=list(minp())
d=Counter(a)
flag=0
for keys in d:
    if d[keys]&1:
        flag=1
        break
if flag:
    print(-1)
    exit(0)
d={}
for i in range(2*n):
    try:
        d[a[i]].append(i+1)
    except:
        d[a[i]]=[i+1]
for keys in d:
    print(*d[keys])
```


327_B. Hungry Sequence

Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers.

A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if:

  * Its elements are in increasing order. That is an inequality ai < aj holds for any two indices i, j (i < j).
  * For any two indices i and j (i < j), aj must not be divisible by ai.

Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.

Input

The input contains a single integer: n (1 ≤ n ≤ 105).

Output

Output a line that contains n space-separated integers a1 a2, ..., an (1 ≤ ai ≤ 107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1.

If there are multiple solutions you can output any one.

Examples

Input

3

Output

2 9 15

Input

5

Output

11 14 20 27 31

```python
n=int(input())
for i in range(n,n+n):
    print(i,end=' ')
```


349_C. Mafia

One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?

Input

The first line contains integer n (3 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the i-th number in the list is the number of rounds the i-th person wants to play.

Output

In a single line print a single integer — the minimum number of game rounds the friends need to let the i-th person play at least ai rounds.

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

Examples

Input

3
3 2 2

Output

4

Input

4
2 2 2 2

Output

3

Note

You don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).

```python
def ceil(x):
    if int(x) != x:
        return int(x+1)
    else:
        return int(x)

def mafia():
    n = int(input())
    rounds = list(map(int, str(input()).split()))
    count = 0
    rounds.sort(reverse=True)
    for i in range(n-1, 0, -1):
        if rounds[i-1] == rounds[i]:
            continue
        else:
            steps = n - i
            count += steps*(rounds[i-1] - rounds[i])
    rounds[0] -= count
    if rounds[0] > 0:
        k = ceil(rounds[0] / (n - 1))
        count += n * k
        rounds[0] += k * (1 - n)
    if rounds[0] <= 0:
        count += rounds[0]
    print(count)

if __name__ == '__main__':
    mafia()

```


394_A. Counting Sticks

When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add and subtract? — That's right, using counting sticks! An here's our new task:

An expression of counting sticks is an expression of type:

[ A sticks][sign +][B sticks][sign =][C sticks] (1 ≤ A, B, C).

Sign + consists of two crossed sticks: one vertical and one horizontal. Sign = consists of two horizontal sticks. The expression is arithmetically correct if A + B = C.

We've got an expression that looks like A + B = C given by counting sticks. Our task is to shift at most one stick (or we can shift nothing) so that the expression became arithmetically correct. Note that we cannot remove the sticks from the expression, also we cannot shift the sticks from the signs + and =.

We really aren't fabulous at arithmetics. Can you help us?

Input

The single line contains the initial expression. It is guaranteed that the expression looks like A + B = C, where 1 ≤ A, B, C ≤ 100.

Output

If there isn't a way to shift the stick so the expression becomes correct, print on a single line "Impossible" (without the quotes). If there is a way, print the resulting expression. Follow the format of the output from the test samples. Don't print extra space characters.

If there are multiple correct answers, print any of them. For clarifications, you are recommended to see the test samples.

Examples

Input

||+|=|||||

Output

|||+|=||||

Input

|||||+||=||

Output

Impossible

Input

|+|=||||||

Output

Impossible

Input

||||+||=||||||

Output

||||+||=||||||

Note

In the first sample we can shift stick from the third group of sticks to the first one.

In the second sample we cannot shift vertical stick from + sign to the second group of sticks. So we cannot make a - sign.

There is no answer in the third sample because we cannot remove sticks from the expression.

In the forth sample the initial expression is already arithmetically correct and that is why we don't have to shift sticks.

```python
v = input().split('+')
a = len(v[0])
v = v[1].split('=')
b = len(v[0])
c = len(v[1])

def good(a, b, c):
    return a+b==c and a>0 and b>0 and c>0

if good(a-1, b, c+1):
    a = a-1
    c = c+1

if good(a, b-1, c+1):
    b = b-1
    c = c+1

if good(a+1, b, c-1):
    a = a+1
    c = c-1

if good(a, b+1, c-1):
    b = b+1
    c = c-1

if a+b==c:
    print('|'*a+'+'+'|'*b+'='+'|'*c)
else:
    print("Impossible")

```


417_B. Crash

During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.

Each participant is identified by some unique positive integer k, and each sent solution A is characterized by two numbers: x — the number of different solutions that are sent before the first solution identical to A, and k — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same x.

It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number x (x > 0) of the participant with number k, then the testing system has a solution with number x - 1 of the same participant stored somewhere before.

During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.

Input

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the number of solutions. Each of the following n lines contains two integers separated by space x and k (0 ≤ x ≤ 105; 1 ≤ k ≤ 105) — the number of previous unique solutions and the identifier of the participant.

Output

A single line of the output should contain «YES» if the data is in chronological order, and «NO» otherwise.

Examples

Input

2
0 1
1 1

Output

YES

Input

4
0 1
1 2
1 1
0 2

Output

NO

Input

4
0 1
1 1
0 1
0 2

Output

YES

```python
def readln(): return tuple(map(int, input().split()))

n, = readln()
max_pref = [-1] * 100001
flag = True
for _ in range(n):
    x, k = readln()
    flag &= max_pref[k] + 1 >= x
    max_pref[k] = max(max_pref[k], x)
print('YES' if flag else 'NO')
```


443_E. Artem and Array

Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.

After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

Input

The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers ai (1 ≤ ai ≤ 106) — the values of the array elements.

Output

In a single line print a single integer — the maximum number of points Artem can get.

Examples

Input

5
3 1 5 2 6

Output

11

Input

5
1 2 3 4 5

Output

6

Input

5
1 100 101 100 1

Output

102

```python
n = input()
s = []
a = 0
for i in map(int, input().split()):
    while len(s) > 1 and min(s[-2], i)>=s[-1]:
        a += min(i, s[-2])
        del(s[-1])
    s.append(i)
s.sort()
print(a + sum(s[0: -2]))

```


466_A. Cheap Travel

Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of money she will have to spend to make n rides?

Input

The single line contains four space-separated integers n, m, a, b (1 ≤ n, m, a, b ≤ 1000) — the number of rides Ann has planned, the number of rides covered by the m ride ticket, the price of a one ride ticket and the price of an m ride ticket.

Output

Print a single integer — the minimum sum in rubles that Ann will need to spend.

Examples

Input

6 2 1 2

Output

6

Input

5 2 2 3

Output

8

Note

In the first sample one of the optimal solutions is: each time buy a one ride ticket. There are other optimal solutions. For example, buy three m ride tickets.

```python
inp = input().split()
n = int(inp[0])
m = int(inp[1])
a = int(inp[2])
b = int(inp[3])
sumary = min(b,a*m)
print(min((sumary)*(n//m + 1), sumary*(n // m) + (n - (n//m)*m) * a ))
```


489_E. Hiking

A traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the i-th rest point the distance from the start equals xi, and its picturesqueness equals bi. The traveler will move down the river in one direction, we can assume that he will start from point 0 on the coordinate axis and rest points are points with coordinates xi.

Every day the traveler wants to cover the distance l. In practice, it turns out that this is not always possible, because he needs to end each day at one of the resting points. In addition, the traveler is choosing between two desires: cover distance l every day and visit the most picturesque places.

Let's assume that if the traveler covers distance rj in a day, then he feels frustration <image>, and his total frustration over the hike is calculated as the total frustration on all days.

Help him plan the route so as to minimize the relative total frustration: the total frustration divided by the total picturesqueness of all the rest points he used.

The traveler's path must end in the farthest rest point.

Input

The first line of the input contains integers n, l (1 ≤ n ≤ 1000, 1 ≤ l ≤ 105) — the number of rest points and the optimal length of one day path.

Then n lines follow, each line describes one rest point as a pair of integers xi, bi (1 ≤ xi, bi ≤ 106). No two rest points have the same xi, the lines are given in the order of strictly increasing xi.

Output

Print the traveler's path as a sequence of the numbers of the resting points he used in the order he used them. Number the points from 1 to n in the order of increasing xi. The last printed number must be equal to n.

Examples

Input

5 9
10 10
20 10
30 1
31 5
40 10

Output

1 2 4 5

Note

In the sample test the minimum value of relative total frustration approximately equals 0.097549. This value can be calculated as <image>.

```python
import os
import sys
if os.path.exists(r'C:\Users\User\codeforces'):
    f = iter(open('A.txt').readlines())
    def input():
        return next(f).strip()
    # input = lambda: sys.stdin.readline().strip()
else:
    input = lambda: sys.stdin.readline().strip()

fprint = lambda *args: print(*args, flush=True)

from math import sqrt
n, l = map(int, input().split())
x, b = [0], [0]
for _ in range(n):
    u, v = map(int, input().split())
    x.append(u)
    b.append(v)

def check(V):
    values = [2*10**9] * (n+1)
    values[0] = 0
    for i in range(1, n+1):
        for p in range(i):
            values[i] = min(values[i], values[p] + sqrt(abs(x[i]-x[p]-l)) - V * b[i])
    return values[-1] <= 0

def get(V):
    values = [2*10**9] * (n+1)
    values[0] = 0
    prev = [-1] * (n+1)
    for i in range(1, n+1):
        for p in range(i):
            q = values[p] + sqrt(abs(x[i]-x[p]-l)) - V * b[i]
            if q < values[i]:
                prev[i] = p
                values[i] = q
    res = [n]
    while res[-1] != 0:
        res.append(prev[res[-1]])
    res.pop()
    return res

eps = 1e-9
R, L = 10**3+1, 0
while R - L > eps:
    # print(R, L)
    m = (R+L)/2
    if check(m):
        R = m
    else:
        L = m

print(' '.join(map(str, reversed(get(R)))))
```


513_C. Second price auction

Nowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple companies compete for each ad slot on the web page in an auction. Each of them receives a request with details about the user, web page and ad slot and they have to respond within those 100 milliseconds with a bid they would pay for putting an advertisement on that ad slot. The company that suggests the highest bid wins the auction and gets to place its advertisement. If there are several companies tied for the highest bid, the winner gets picked at random.

However, the company that won the auction does not have to pay the exact amount of its bid. In most of the cases, a second-price auction is used. This means that the amount paid by the company is equal to the maximum of all the other bids placed for this ad slot.

Let's consider one such bidding. There are n companies competing for placing an ad. The i-th of these companies will bid an integer number of microdollars equiprobably randomly chosen from the range between Li and Ri, inclusive. In the other words, the value of the i-th company bid can be any integer from the range [Li, Ri] with the same probability.

Determine the expected value that the winner will have to pay in a second-price auction.

Input

The first line of input contains an integer number n (2 ≤ n ≤ 5). n lines follow, the i-th of them containing two numbers Li and Ri (1 ≤ Li ≤ Ri ≤ 10000) describing the i-th company's bid preferences.

This problem doesn't have subproblems. You will get 8 points for the correct submission.

Output

Output the answer with absolute or relative error no more than 1e - 9.

Examples

Input

3
4 7
8 10
5 5

Output

5.7500000000

Input

3
2 5
3 4
1 6

Output

3.5000000000

Note

Consider the first example. The first company bids a random integer number of microdollars in range [4, 7]; the second company bids between 8 and 10, and the third company bids 5 microdollars. The second company will win regardless of the exact value it bids, however the price it will pay depends on the value of first company's bid. With probability 0.5 the first company will bid at most 5 microdollars, and the second-highest price of the whole auction will be 5. With probability 0.25 it will bid 6 microdollars, and with probability 0.25 it will bid 7 microdollars. Thus, the expected value the second company will have to pay is 0.5·5 + 0.25·6 + 0.25·7 = 5.75.

```python
import sys

MaxV = int(1e4)

data = []
readIdx = 0
for line in sys.stdin.readlines():
	data += line.split()

def read():
	global readIdx
	readIdx += 1
	return data[readIdx - 1]

n, average, power, mul = int(read()), 0, 1, 1
froms, tos, r = [], [], []

def generate(i, maxIdx, secondMax, equal, ways):
	global n, r
	if i < n:
		for state in range(3):
			if state < 2:
				newWays = ways
				newEqual = equal
				if state == 0:
					newWays *= max(0, min(secondMax - 1, tos[i]) + 1 - froms[i])
				else:
					newEqual += 1
					if froms[i] > secondMax or tos[i] < secondMax:
						newWays = 0
				if newWays > 0:
					generate(i + 1, maxIdx, secondMax, newEqual, newWays)
			elif maxIdx == None:
				greaterFrom = max(secondMax + 1, froms[i])
				greaterTo = tos[i]
				newWays = ways
				if greaterFrom > greaterTo:
					newWays = 0
				newWays *= max(0, greaterTo + 1 - greaterFrom)
				if newWays > 0:
					generate(i + 1, i, secondMax, equal, newWays)
	elif ways > 0 and ((maxIdx != None and equal > 0) or (maxIdx == None and equal >= 2)):
		r += [ways * secondMax]

for i in range(n):
	froms += [int(read())]
	tos += [int(read())]
	power *= 3
	mul *= (tos[i] + 1 - froms[i])
for secondMax in range(MaxV + 1):
	generate(0, None, secondMax, 0, 1)
print(sum(r) / mul)

```


538_E. Demiurges Play Again

Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.

There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.

Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.

Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.

Input

The first line contains a single integer n — the number of nodes in the tree (1 ≤ n ≤ 2·105).

Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — the ends of the edge of the tree; the edge leads from node ui to node vi. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.

Output

Print two space-separated integers — the maximum possible and the minimum possible result of the game.

Examples

Input

5
1 2
1 3
2 4
2 5

Output

3 2

Input

6
1 2
1 3
3 4
1 5
5 6

Output

3 3

Note

Consider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.

In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3.

```python
import sys

input = sys.stdin.readline

def solve():
	n = int(input())
	g = [[] for i in range(n+1)]
	for i in range(1, n):
		u, v = map(int, input().split())
		g[u].append(v)
		g[v].append(u)
	q = [1]
	d = [None]*(n+1)
	d[1] = 0
	i = 0
	while i < len(q):
		x = q[i]
		#print(x)
		i += 1
		for v in g[x]:
			if d[v] is None:
				q.append(v)
				d[v] = d[x] + 1
				g[v].remove(x)
	m = [0]*(n+1)
	M = [0]*(n+1)
	cnt = 0
	for i in range(len(q)-1,-1,-1):
		x = q[i]
		if len(g[x]) == 0:
			m[x] = 1
			M[x] = 1
			cnt += 1
		elif d[x] % 2 == 0:
			c = 0
			C = int(1e9)
			for v in g[x]:
				c += m[v]
			for v in g[x]:
				C = min(C, M[v])
			m[x] = c
			M[x] = C
		else:
			c = int(1e9)
			C = 0
			for v in g[x]:
				c = min(c, m[v])
			for v in g[x]:
				C += M[v]
			m[x] = c
			M[x] = C
	print(cnt + 1 - M[x], m[1])

solve()

```


566_F. Clique in the Divisibility Graph

As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.

Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.

Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.

You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.

Input

The first line contains integer n (1 ≤ n ≤ 106), that sets the size of set A.

The second line contains n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 106) — elements of subset A. The numbers in the line follow in the ascending order.

Output

Print a single number — the maximum size of a clique in a divisibility graph for set A.

Examples

Input

8
3 4 6 8 10 18 21 24

Output

3

Note

In the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.

```python
for _ in range(1):
    n=int(input())
    l=list(map(int,input().split()))
    dp=[0]*(10**6+1)
    for i in l:
        dp[i]=1
    for i in l:
        if dp[i]:
            for x in range(i*2,10**6+1,i):
                if dp[x]:
                    dp[x]=max(dp[x],dp[i]+1)
    print(max(dp))

```


588_A. Duff and Meat

Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.

<image>

There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ..., an and p1, ..., pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.

Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

Input

The first line of input contains integer n (1 ≤ n ≤ 105), the number of days.

In the next n lines, i-th line contains two integers ai and pi (1 ≤ ai, pi ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

Output

Print the minimum money needed to keep Duff happy for n days, in one line.

Examples

Input

3
1 3
2 2
3 1

Output

10

Input

3
1 3
2 1
3 2

Output

8

Note

In the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.

In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

```python
n=int(input())
y,s=101,0
for i in range(n):
    a,b=map(int,input().split())
    if y>b:
        y=b
    s+=(a*y)
print(s)
```


630_H. Benches

The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.

The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Obviously this requirement is satisfied by the following scheme: each bench is placed on a cross of paths and each path contains not more than one bench.

Help the park administration count the number of ways to place the benches.

Input

The only line of the input contains one integer n (5 ≤ n ≤ 100) — the number of east to west paths and north to south paths.

Output

Output one integer — the number of ways to place the benches.

Examples

Input

5

Output

120

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

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
# n=int(input())
# n,k=map(int,input().split())
# arr=list(map(int,input().split()))
#ls=list(map(int,input().split()))
#for i in range(m):
# for _ in range(int(input())):
#from collections import Counter
#from fractions import Fraction
#s=iter(input())
#from collections import deque
import math
#for _ in range(int(input())):
n=int(input())
var=n**2*(n-1)**2*(n-2)**2*(n-3)**2*(n-4)**2
print(var//120)

```


681_B. Economy Game

Kolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to 0.

Kolya remembers that at the beginning of the game his game-coin score was equal to n and that he have bought only some houses (for 1 234 567 game-coins each), cars (for 123 456 game-coins each) and computers (for 1 234 game-coins each).

Kolya is now interested, whether he could have spent all of his initial n game-coins buying only houses, cars and computers or there is a bug in the game. Formally, is there a triple of non-negative integers a, b and c such that a × 1 234 567 + b × 123 456 + c × 1 234 = n?

Please help Kolya answer this question.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 109) — Kolya's initial game-coin score.

Output

Print "YES" (without quotes) if it's possible that Kolya spent all of his initial n coins buying only houses, cars and computers. Otherwise print "NO" (without quotes).

Examples

Input

1359257

Output

YES

Input

17851817

Output

NO

Note

In the first sample, one of the possible solutions is to buy one house, one car and one computer, spending 1 234 567 + 123 456 + 1234 = 1 359 257 game-coins in total.


704_A. Thor

Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).

q events are about to happen (in chronological order). They are of three types:

  1. Application x generates a notification (this new notification is unread).
  2. Thor reads all notifications generated so far by application x (he may re-read some notifications).
  3. Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.

Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.

Input

The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen.

The next q lines contain the events. The i-th of these lines starts with an integer typei — type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 ≤ typei ≤ 3, 1 ≤ xi ≤ n, 1 ≤ ti ≤ q).

Output

Print the number of unread notifications after each event.

Examples

Input

3 4
1 3
1 1
1 2
2 3

Output

1
2
3
2

Input

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

Output

1
2
3
0
1
2

Note

In the first sample:

  1. Application 3 generates a notification (there is 1 unread notification).
  2. Application 1 generates a notification (there are 2 unread notifications).
  3. Application 2 generates a notification (there are 3 unread notifications).
  4. Thor reads the notification generated by application 3, there are 2 unread notifications left.

In the second sample test:

  1. Application 2 generates a notification (there is 1 unread notification).
  2. Application 4 generates a notification (there are 2 unread notifications).
  3. Application 2 generates a notification (there are 3 unread notifications).
  4. Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.
  5. Application 3 generates a notification (there is 1 unread notification).
  6. Application 3 generates a notification (there are 2 unread notifications).

```python
n , q = map(int, input().split())
stacks = [[] for i in range(n + 1)]
queue = []
q_start = 0
unread = 0
ans = []

for i in range(q):
    action, num = map(int, input().split())
    if action == 1:
        queue.append(0)
        stacks[num].append(len(queue) - 1)
        unread += 1

    elif action == 2:
        for i in range(len(stacks[num])):
            if stacks[num][i] >= q_start and queue[stacks[num][i]] == 0:
                queue[stacks[num][i]] = 1
                unread -= 1
        stacks[num] = []
    else:
        for i in range(q_start, num):
            if queue[i] == 0:
                queue[i] = 1
                unread -= 1
        q_start = max(q_start, num)
    ans.append(unread)

print("\n".join(map(str, ans)))
```


725_F. Family Photos

Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.

There are n stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks.

Each photo is described by two non-negative integers a and b, indicating that it is worth a units of happiness to Alice and b units of happiness to Bonnie. Values of a and b might differ for different photos.

It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.

The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has x happiness and Bonnie has y happiness at the end, you should print x - y.

Input

The first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the number of two-photo stacks. Then follow n lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers a1, b1, a2 and b2, each not exceeding 109. a1 and b1 describe the top photo in the stack, while a2 and b2 describe the bottom photo in the stack.

Output

Output a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.

Examples

Input

2
12 3 4 7
1 15 9 1

Output

1

Input

2
5 4 8 8
4 12 14 0

Output

4

Input

1
0 10 0 10

Output

-10

```python
num_stacks = int(input())

answer = 0
array = []

for i in range(num_stacks):
    a1, b1, a2, b2 = input().split(' ')
    a1 = int(a1)
    a2 = int(a2)
    b1 = int(b1)
    b2 = int(b2)

    if a1 + b1 >= a2 + b2:
        answer += a1 + a2
        array.append(a2 + b2)
        array.append(a1 + b1)

    elif a1 > b2:
        answer += a1 - b2

    elif b1 > a2:
        answer += a2 - b1

    # Elif both side skip

array.sort()

for i in range(0, len(array), 2):
    answer -= array[i]

print(answer)
```


770_C. Online Courses In BSU

Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage.

The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).

Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses.

Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once.

Input

The first line contains n and k (1 ≤ k ≤ n ≤ 105) — the number of online-courses and the number of main courses of Polycarp's specialty.

The second line contains k distinct integers from 1 to n — numbers of main online-courses of Polycarp's specialty.

Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≤ ti ≤ n - 1) — the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n — numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself.

It is guaranteed that the sum of all values ti doesn't exceed 105.

Output

Print -1, if there is no the way to get a specialty.

Otherwise, in the first line print the integer m — the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers — numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them.

Examples

Input

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

Output

5
1 2 3 4 5

Input

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

Output

6
1 2 9 4 5 3

Input

3 3
1 2 3
1 2
1 3
1 1

Output

-1

Note

In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course.

```python
f = lambda: map(int, input().split())
g = lambda: [[] for x in range(n)]
n, k = f()
n += 1

s, p = [], list(f())
c, d = [0] * n, [0] * n
u, v = g(), g()

for x in range(1, n):
    t = list(f())
    m = t.pop(0)
    if m:
        c[x] = m
        v[x] = t
        for y in t: u[y].append(x)
    else:
        s.append(x)
        d[x] = 1
while s:
    x = s.pop()
    for y in u[x]:
        c[y] -= 1
        d[y] = max(d[y], d[x] + 1)
        if c[y] == 0: s.append(y)

if any(c[x] for x in p):
    print(-1)
    exit()

q = [0] * n
while p:
    x = p.pop()
    if q[x] == 0:
        p += v[x]
        q[x] = 1

p = sorted((d[x], x) for x in range(n) if q[x])
print(len(p))
for d, x in p: print(x)
```


862_A. Mahmoud and Ehab and the MEX

Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go.

Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of a set of integers is the minimum non-negative integer that doesn't exist in it. For example, the MEX of the set {0, 2, 4} is 1 and the MEX of the set {1, 2, 3} is 0 .

Dr. Evil is going to make his set evil. To do this he can perform some operations. During each operation he can add some non-negative integer to his set or erase some element from it. What is the minimal number of operations Dr. Evil has to perform to make his set evil?

Input

The first line contains two integers n and x (1 ≤ n ≤ 100, 0 ≤ x ≤ 100) — the size of the set Dr. Evil owns, and the desired MEX.

The second line contains n distinct non-negative integers not exceeding 100 that represent the set.

Output

The only line should contain one integer — the minimal number of operations Dr. Evil should perform.

Examples

Input

5 3
0 4 5 6 7

Output

2

Input

1 0
0

Output

1

Input

5 0
1 2 3 4 5

Output

0

Note

For the first test case Dr. Evil should add 1 and 2 to the set performing 2 operations.

For the second test case Dr. Evil should erase 0 from the set. After that, the set becomes empty, so the MEX of it is 0.

In the third test case the set is already evil.

```python
n,m = map(int, input().split())
s = set([int(i) for i in input().split()])
ans = 0
for i in range (m):
    if i not in s:
        ans += 1
print(ans+1 if m in s else ans)
```


959_C. Mahmoud and Ehab and the wrong algorithm

Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:

Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm:

  * Root the tree at node 1.
  * Count the number of nodes at an even depth. Let it be evenCnt.
  * Count the number of nodes at an odd depth. Let it be oddCnt.
  * The answer is the minimum between evenCnt and oddCnt.

The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.

Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.

Input

The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees.

Output

The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only.

If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict.

If there are multiple answers, you can print any of them.

Examples

Input

2

Output

-1
1 2

Input

8

Output

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

Note

In the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed  - 1 in the first section, but notice that we printed this tree in the second section.

In the second sample:

In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this: <image> In the second tree, the algorithm will find an answer with 3 nodes which is correct: <image>

```python
n = int(input())
if n <= 5:
    print(-1)
else:
    print('1 2', '1 3', '1 4', '2 5', sep = '\n')
    for i in range(6, n + 1):
        print('2 {0:d}'.format(i))
for i in range(2, n + 1):
    print('1 {0:d}'.format(i))

```


p02581 AtCoder Beginner Contest 176 - Brave CHAIN

We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i.

You will do the following operation N-1 times:

* Rearrange the five leftmost cards in any order you like, then remove the three leftmost cards. If the integers written on those three cards are all equal, you gain 1 point.

After these N-1 operations, if the integers written on the remaining three cards are all equal, you will gain 1 additional point.

Find the maximum number of points you can gain.

Constraints

* 1 \leq N \leq 2000
* 1 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_{3N}

Output

Print the maximum number of points you can gain.

Examples

Input

2
1 2 1 2 2 1

Output

2

Input

3
1 1 2 2 3 3 3 2 1

Output

1

Input

3
1 1 2 2 2 3 3 3 1

Output

3

```python
N = int(input())
A = [int(a) for a in input().split()] + [0] * 2
X = [[-10**10] * (N+1) for _ in range(N+1)]
X[A[0]][A[1]] = 0
ans = 0
ma = 0
MA = [-5] * (N+1)
MA[A[0]] = MA[A[1]] = 0
for i in range(N):
    B = A[i*3+2:i*3+5]
    cnt = len(set(B))
    if cnt == 1:
        ans += 1
    elif cnt == 2:
        a1 = B[0]^B[1]^B[2]
        a2 = (sum(B) - a1) // 2
        X[a1], X[a1][a2], X[a2][a2] = [max(X[a2][j] + 1, X[j][a2] + 1, MA[j]) for j in range(N+1)], max(ma, X[a2][a2] + 1), max(ma, X[a1][a1] + 1)
        X[a2] = [max(x, m) for x, m in zip(X[a2], MA)]
        MA = [max(m, x1, x2) for m, x1, x2 in zip(MA, X[a1], X[a2])]
        MA[a1] = max(MA[a1], max(X[a1]))
        MA[a2] = max(MA[a2], X[a1][a2], X[a2][a2])
        ma = max(ma, MA[a1], MA[a2])
    else:
        a, b, c = B
        X[a][b], X[a][c], X[b][c] = max(ma, X[c][c] + 1), max(ma, X[b][b] + 1), max(ma, X[a][a] + 1)
        X[a] = [max(x, m) for x, m in zip(X[a], MA)]
        X[b] = [max(x, m) for x, m in zip(X[b], MA)]
        X[c] = [max(x, m) for x, m in zip(X[c], MA)]
        MA[a] = max(MA[a], max(X[a]))
        MA[b] = max(MA[b], X[a][b], max(X[b]))
        MA[c] = max(MA[c], X[a][c], X[b][c], max(X[c]))
        MA = [max(m, xa, xb, xc) for m, xa, xb, xc in zip(MA, X[a], X[b], X[c])]
        ma = max(ma, MA[a], MA[b], MA[c])

print(ans + max(ma, max(max(x) for x in X)))
```


p02712 AtCoder Beginner Contest 162 - FizzBuzz Sum

Let us define the FizzBuzz sequence a_1,a_2,... as follows:

* If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.
* If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.
* If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.
* If none of the above holds, a_i=i.

Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

Constraints

* 1 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

Examples

Input

15

Output

60

Input

1000000

Output

266666333332

```python
N = int(input())
s = sum([i for i in range(1, N+1) if ((i%3)!=0) and ((i%5)!=0)])
print(s)
```


p02841 Sumitomo Mitsui Trust Bank Programming Contest 2019 - November 30

In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019.

Integers M_1, D_1, M_2, and D_2 will be given as input.
It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1.
Determine whether the date 2019-M_1-D_1 is the last day of a month.

Constraints

* Both 2019-M_1-D_1 and 2019-M_2-D_2 are valid dates in the Gregorian calendar.
* The date 2019-M_2-D_2 follows 2019-M_1-D_1.

Input

Input is given from Standard Input in the following format:

M_1 D_1
M_2 D_2

Output

If the date 2019-M_1-D_1 is the last day of a month, print `1`; otherwise, print `0`.

Examples

Input

11 16
11 17

Output

0

Input

11 30
12 1

Output

1

```python
input()
_, d = input().split()
print('1' if d == '1' else '0')

```


p02978 AtCoder Grand Contest 035 - Add and Remove

There is a stack of N cards, each of which has a non-negative integer written on it. The integer written on the i-th card from the top is A_i.

Snuke will repeat the following operation until two cards remain:

* Choose three consecutive cards from the stack.
* Eat the middle card of the three.
* For each of the other two cards, replace the integer written on it by the sum of that integer and the integer written on the card eaten.
* Return the two cards to the original position in the stack, without swapping them.

Find the minimum possible sum of the integers written on the last two cards remaining.

Constraints

* 2 \leq N \leq 18
* 0 \leq A_i \leq 10^9 (1\leq i\leq N)
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sum of the integers written on the last two cards remaining.

Examples

Input

4
3 1 4 2

Output

16

Input

6
5 2 4 1 6 9

Output

51

Input

10
3 1 4 1 5 9 2 6 5 3

Output

115

```python
#YouTube
import sys
sys.setrecursionlimit(10**6)

def kukan(l,r,el=1,er=1):
    em=el+er
    if l+1==r:
        return 0
    if l+2==r:
        return a[l+1]*em
    t=(l,r,el,er)
    if t in memo:
        return memo[t]
    re=10**11
    for m in range(l+1,r):
        tmp=kukan(l,m,el,em)+kukan(m,r,em,er)+a[m]*em
        if tmp<re:
            re=tmp
    memo[t]=re
    return re

n=int(input())
a=list(map(int,input().split()))
memo={}
print(a[0]+kukan(0,n-1)+a[-1])
```


p03118 World Tour Finals 2019 Open Contest - e

There is a very long bench. The bench is divided into M sections, where M is a very large integer.

Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action:

* We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied sections. If there is no comfortable section, the person leaves the bench. Otherwise, the person chooses one of comfortable sections uniformly at random, and sits there. (The choices are independent from each other).

After all M people perform actions, Snuke chooses an interval of N consecutive sections uniformly at random (from M-N+1 possible intervals), and takes a photo. His photo can be described by a string of length N consisting of `X` and `-`: the i-th character of the string is `X` if the i-th section from the left in the interval is occupied, and `-` otherwise. Note that the photo is directed. For example, `-X--X` and `X--X-` are different photos.

What is the probability that the photo matches a given string s? This probability depends on M. You need to compute the limit of this probability when M goes infinity.

Here, we can prove that the limit can be uniquely written in the following format using three rational numbers p, q, r and e = 2.718 \ldots (the base of natural logarithm):

p + \frac{q}{e} + \frac{r}{e^2}

Your task is to compute these three rational numbers, and print them modulo 10^9 + 7, as described in Notes section.

Constraints

* 1 \leq N \leq 1000
* |s| = N
* s consists of `X` and `-`.

Input

Input is given from Standard Input in the following format:

N
s

Output

Print three rational numbers p, q, r, separated by spaces.

Examples

Input

1
X

Output

500000004 0 500000003

Input

3
---

Output

0 0 0

Input

5
X--X-

Output

0 0 1

Input

5
X-X-X

Output

500000004 0 833333337

Input

20
-X--X--X-X--X--X-X-X

Output

0 0 183703705

Input

100
X-X-X-X-X-X-X-X-X-X--X-X-X-X-X-X-X-X-X-X-X-X-X-X-X--X--X-X-X-X--X--X-X-X--X-X-X--X-X--X--X-X--X-X-X-

Output

0 0 435664291

```python
#参考URL
#https://qiita.com/ageprocpp/items/104c051b2ec2086f5a9b

mod=10**9+7
def value(obj):
    if type(obj)==modint:
        tmp=obj.number
    else:
        tmp=obj
    return tmp%mod
class modint():
    number=0
    def __init__(self,num):
        self.number=num%mod
    def __add__(self,other):
        tmp=value(other)
        return modint(self.number+tmp)
    def __iadd__(self,other):
        tmp=value(other)
        self.number+=tmp
        self.number%=mod
        return self
    def __sub__(self,other):
        tmp=value(other)
        return modint(self.number-tmp)
    def __isub__(self,other):
        tmp=value(other)
        self.number-=tmp
        self.number%=mod
        return self
    def __mul__(self,other):
        tmp=value(other)
        return modint(self.number*tmp)
    def __imul__(self,other):
        tmp=value(other)
        self.number*=tmp
        self.number%=mod
        return self
    def __truediv__(self,other):
        tmp=value(other)
        return self*pow(tmp,mod-2,mod)
    def __itruediv(self,other):
        tmp=value(other)
        self.number=self/tmp
        self.number%=mod
        return self
    def __repr__(self):
        return str(self.number)
    def __eq__(self,other):
        return value(self)==value(other)
    def __ne__(self,other):
        return value(self)!=value(other)
    def __str__(self):
        return str(self.number)
    def __int__(self):
        return self.number
    def __hash__(self):
        return self.number

class polynomial():
    sequence=[0]
    def __init__(self,seq):
        self.sequence=[]
        for i in seq:
            self.sequence.append(value(i))
    def get(self,x):
        res=modint(0)
        tmp=modint(1)
        for a in self.sequence:
            res+=tmp*a
            tmp*=x
            if tmp==0:
                break
        return res
    def __add__(self,other):
        res=[]
        for i,a in enumerate(self.sequence):
            try:
                res[i]=a
            except IndexError:
                res.append(modint(0))
                res[i]=a
        for i,a in enumerate(other.sequence):
            try:
                res[i]+=a
            except IndexError:
                res.append(modint(0))
                res[i]+=a

        return polynomial(res)
    def __iadd__(self,other):
        return self+other
    def __sub__(self,other):
        res=[]
        for i,a in enumerate(self.sequence):
            try:
                res[i]=a
            except IndexError:
                res.append(modint(0))
                res[i]=a
        for i,a in enumerate(other.sequence):
            try:
                res[i]-=a
            except IndexError:
                res.append(modint(0))
                res[i]-=a
        return polynomial(res)
    def __isub__(self,other):
        return self-other
    def indef_integral(self):
        res=[modint(0)]
        for i,a in enumerate(self.sequence):
            res.append(modint(a)/(i+1))
        return polynomial(res)
    def integrate(self,flag):
        #0: 0->x
        #1:x->1
        if flag==0:
            return self.indef_integral()
        else:
            tmp=self.indef_integral()
            return polynomial([tmp.get(1)])-tmp
    def __repr__(self):
        return str(self.sequence)
    def __str__(self):
        return str(self.sequence)

class func():
    P=polynomial([modint(0)])
    Q=polynomial([modint(0)])
    C=modint(0)
    def __init__(self,poly1,poly2,cnst):
        self.P=poly1
        self.Q=poly2
        self.C=cnst
    def __add__(self,other):
        PP=self.P+other.P
        QQ=self.Q+other.Q
        CC=self.C+other.C
        return func(PP,QQ,CC)
    def __iadd__(self,other):
        return self+other
    def __sub__(self,other):
        PP=self.P-other.P
        QQ=self.Q-other.Q
        CC=self.C-other.C
        return func(PP,QQ,CC)
    def __isub__(self,other):
        return self-other
    def dintegrate(self,flag):
        if flag==0:
            PP=self.P.integrate(0)+polynomial([self.C])
            QQ=self.Q.integrate(0)
            CC=modint(-1)*self.C
        else:
            PP=self.P.integrate(1)
            QQ=self.Q.integrate(1)+polynomial([modint(-1)*self.C])
            CC=self.C
        return func(PP,QQ,CC)
MAX_N=1009
N=int(input())
s=input()
fact=[modint(0) for i in range(MAX_N+1)]
inv=[modint(0) for i in range(MAX_N+1)]
fact[0]=modint(1)
for i in range(MAX_N):
    fact[i+1]=fact[i]*(i+1)
inv[-1]=modint(1)/fact[-1]
for i in range(MAX_N-1,-1,-1):
    inv[i]=inv[i+1]*(i+1)
dp=[[[[func(polynomial([modint(0)]),polynomial([modint(0)]),modint(0)) for l in range(2)]for k in range(2)]for j in range(2)] for i in range(MAX_N+1)]

if s[0]=="X":
    dp[0][0][1][0]=func(polynomial([modint(0)]),polynomial([modint(0)]),modint(1))
else:
    dp[0][0][0][1]=func(polynomial([modint(0)]),polynomial([modint(0)]),modint(1))
    dp[0][1][1][1]=func(polynomial([modint(1)]),polynomial([modint(0)]),modint(-1))
for i in range(1,N):
    if s[i]=="X":
        dp[i][0][1][0]+=dp[i-1][1][1][0].dintegrate(0)
        dp[i][0][1][0]+=dp[i-1][1][1][1].dintegrate(0)
        dp[i][0][1][0]+=dp[i-1][0][0][1].dintegrate(1)
        dp[i][0][1][0]+=dp[i-1][0][1][1].dintegrate(1)
        dp[i][0][1][0]+=dp[i-1][1][0][1].dintegrate(1)
        dp[i][0][1][0]+=dp[i-1][1][1][1].dintegrate(1)
    else:
        dp[i][0][0][1]+=dp[i-1][1][1][0].dintegrate(0)
        dp[i][0][0][1]+=dp[i-1][1][1][1].dintegrate(0)
        dp[i][1][1][1]+=dp[i-1][0][1][0].dintegrate(0)
        dp[i][1][1][1]+=dp[i-1][0][1][1].dintegrate(0)
        dp[i][0][0][1]+=dp[i-1][0][1][0].dintegrate(1)
        dp[i][0][0][1]+=dp[i-1][0][1][1].dintegrate(1)
        dp[i][0][0][1]+=dp[i-1][1][1][0].dintegrate(1)
        dp[i][0][0][1]+=dp[i-1][1][1][1].dintegrate(1)
a=modint(0)
b=modint(0)
c=modint(0)

p = dp[N-1][0][1][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][0][1][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][0][1][1].C
b-= dp[N-1][0][1][1].C
p = dp[N-1][1][1][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][1][1][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][1][1][1].C
b-= dp[N-1][1][1][1].C
for x in range(2):
    for i,v in enumerate(dp[N-1][x][1][0].P.sequence):
        a+=modint(1)*v*fact[i]
        for j in range(i+1):
            b-=modint(1)*v*fact[i]*inv[j]
    for i,v in enumerate(dp[N-1][x][1][0].Q.sequence):
        b+=modint(1)*v*fact[i]
        for j in range(i+1):
            c-=modint(1)*v*fact[i]*inv[j]
    a+=dp[N-1][x][1][0].C/2
    c-=dp[N-1][x][1][0].C/2

p = dp[N-1][0][0][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][0][0][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][0][0][1].C
b-= dp[N-1][0][0][1].C
p = dp[N-1][1][0][1].P.integrate(0)
a+= p.get(1)-p.get(0)
p = dp[N-1][1][0][1].Q.integrate(0)
b+= p.get(1)-p.get(0)
a+= dp[N-1][1][0][1].C
b-= dp[N-1][1][0][1].C
for x in range(2):
    for i,v in enumerate(dp[N-1][x][0][1].P.sequence):
        a-=modint(1)*v*fact[i]
        for j in range(i+1):
            b+=modint(1)*v*fact[i]*inv[j]
    for i,v in enumerate(dp[N-1][x][0][1].Q.sequence):
        b-=modint(1)*v*fact[i]
        for j in range(i+1):
            c+=modint(1)*v*fact[i]*inv[j]
    a-=dp[N-1][x][0][1].C/2
    c+=dp[N-1][x][0][1].C/2

print(a,b,c)

```


p03261 AtCoder Beginner Contest 109 - Shiritori

Takahashi is practicing shiritori alone again today.

Shiritori is a game as follows:

* In the first turn, a player announces any one word.
* In the subsequent turns, a player announces a word that satisfies the following conditions:
* That word is not announced before.
* The first character of that word is the same as the last character of the last word announced.

In this game, he is practicing to announce as many words as possible in ten seconds.

You are given the number of words Takahashi announced, N, and the i-th word he announced, W_i, for each i. Determine if the rules of shiritori was observed, that is, every word announced by him satisfied the conditions.

Constraints

* N is an integer satisfying 2 \leq N \leq 100.
* W_i is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
W_1
W_2
:
W_N

Output

If every word announced by Takahashi satisfied the conditions, print `Yes`; otherwise, print `No`.

Examples

Input

4
hoge
english
hoge
enigma

Output

No

Input

9
basic
c
cpp
php
python
nadesico
ocaml
lua
assembly

Output

Yes

Input

8
a
aa
aaa
aaaa
aaaaa
aaaaaa
aaa
aaaaaaa

Output

No

Input

3
abc
arc
agc

Output

No

```python
N = int(input())
W = [input() for i in range(N)]
if all(W[i][0]==W[i-1][-1] and W[i] not in W[:i] for i in range(1, N)):
    print('Yes')
else:
    print('No')

```


p03419 AtCoder Regular Contest 091 - Flip Flip  and Flip......

There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region. The front and back sides of these cards can be distinguished, and initially every card faces up.

We will perform the following operation once for each square contains a card:

* For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.

It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed. Find the number of cards that face down after all the operations.

Constraints

* 1 \leq N,M \leq 10^9
* All input values are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of cards that face down after all the operations.

Examples

Input

2 2

Output

0

Input

1 7

Output

5

Input

314 1592

Output

496080

```python
n,m = map(int, input().split())
if n == 1 or m == 1:
    if n == 1 and m == 1:
        print(1)
    else:
        print(max(n,m)-2)
else:
    print((m-2)*(n-2))
```


p03577 CODE FESTIVAL 2017 qual B - XXFESTIVAL

Rng is going to a festival.

The name of the festival is given to you as a string S, which ends with `FESTIVAL`, from input. Answer the question: "Rng is going to a festival of what?" Output the answer.

Here, assume that the name of "a festival of s" is a string obtained by appending `FESTIVAL` to the end of s. For example, `CODEFESTIVAL` is a festival of `CODE`.

Constraints

* 9 \leq |S| \leq 50
* S consists of uppercase English letters.
* S ends with `FESTIVAL`.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer to the question: "Rng is going to a festival of what?"

Examples

Input

CODEFESTIVAL

Output

CODE

Input

CODEFESTIVALFESTIVAL

Output

CODEFESTIVAL

Input

YAKINIKUFESTIVAL

Output

YAKINIKU

```python
# Problem A - XXFESTIVAL
# input
S = input()

# inititliazation
s_len = len(S)
ans = S[:(s_len - 8)]

# output
print(ans)

```


p03734 AtCoder Regular Contest 073 - Simple Knapsack

You have N items and a bag of strength W. The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag. Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

* 1 ≤ N ≤ 100
* 1 ≤ W ≤ 10^9
* 1 ≤ w_i ≤ 10^9
* For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.
* 1 ≤ v_i ≤ 10^7
* W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Examples

Input

4 6
2 1
3 4
4 10
3 4

Output

11

Input

4 6
2 1
3 7
4 10
3 6

Output

13

Input

4 10
1 100
1 100
1 100
1 100

Output

400

Input

4 1
10 100
10 100
10 100
10 100

Output

0

```python
# -*- coding: utf-8 -*-
from itertools import accumulate, product
from operator import itemgetter

def inpl(): return tuple(map(int, input().split()))
N, W = inpl()
I = [inpl() for _ in range(N)]
w1 = I[0][0]
A = {w1 + x: [] for x in range(4)}

for w, v in I:
    A[w].append(v)

for k, v in A.items():
    A[k] = [0] + list(accumulate(sorted(v, reverse=True)))

res = 0
g0 = itemgetter(0)
g1 = itemgetter(1)

for L in product(enumerate(A[w1]),
                 enumerate(A[w1+1]),
                 enumerate(A[w1+2]),
                 enumerate(A[w1+3])):
    if sum([(w1+i)*l for i, l in enumerate(map(g0, L))]) <= W:
        res = max(res, sum(map(g1, L)))

print(res)
```


p03896 CODE FESTIVAL 2016 Relay (Parallel) - 3y3s Challenge

There are N persons, conveniently numbered 1 through N. They will take 3y3s Challenge for N-1 seconds.

During the challenge, each person must look at each of the N-1 other persons for 1 seconds, in some order.

If any two persons look at each other during the challenge, the challenge ends in failure.

Find the order in which each person looks at each of the N-1 other persons, to be successful in the challenge.

Constraints

* 2 \leq N \leq 100

Input

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

N

Output

If there exists no way to be successful in the challenge, print `-1`.

If there exists a way to be successful in the challenge, print any such way in the following format:

A_{1,1} A_{1,2} ... A_{1, N-1}
A_{2,1} A_{2,2} ... A_{2, N-1}
:
A_{N,1} A_{N,2} ... A_{N, N-1}

where A_{i, j} is the index of the person that the person numbered i looks at during the j-th second.

Judging

The output is considered correct only if all of the following conditions are satisfied:

* 1 \leq A_{i,j} \leq N
* For each i, A_{i,1}, A_{i,2}, ... , A_{i, N-1} are pairwise distinct.
* Let X = A_{i, j}, then A_{X, j} \neq i always holds.

Examples

Input

7

Output

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

Input

2

Output

-1

```python
n = int(input())
if n == 2:
    print(-1)
    exit()
if n % 2 == 1:
    for i in range(n):
        print(" ".join([str((item + i + 1) % n + 1) for item in range(n-1)]))
else:
    for i in range(n):
        ans = [(item + i + 1) % n + 1 for item in range(n-1) if item != n // 2 - 1]
        ans.insert(0, (n // 2 + i) % n + 1)
        if i < n // 2:
            ans[0], ans[1] = ans[1], ans[0]
        print(" ".join([str(item) for item in ans]))
```


p00002 Digit Number

Write a program which computes the digit number of sum of two integers a and b.

Constraints

* 0 ≤ a, b ≤ 1,000,000
* The number of datasets ≤ 200

Input

There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF.

Output

Print the number of digits of a + b for each data set.

Example

Input

5 7
1 99
1000 999

Output

2
3
4

```python
while 1:
    try:
        a,b=map(int,input().split())
        print(len(str(a+b)))
    except: break
```


p00134 Exit Survey

I conducted an exit poll of the shopping amount at a department store. Create a program that takes the shopping amount data as input, calculates the average shopping amount per person, and outputs it. The number of people surveyed shall be 100,000 or less, and the shopping amount per person shall not exceed 1 million yen.

Input

The input is given in the following format:

n
v1
v2
::
vn

The first line gives the number of people surveyed n, and the following n lines give the integer vi representing the purchase amount of the ith person.

Output

Please output the average shopping amount (integer: rounded down to the nearest whole number) on one line.

Example

Input

6
12300
5600
33800
0
26495
52000

Output

21699

```python
# AOJ 0134 Exit Survey
# Python3 2018.6.18 bal4u

sum = 0
n = int(input())
for i in range(n):
	sum += int(input())
print(sum // n)

```


p00267 The Lonely Girl's Lie

There is a game called Packet Monster. A game that catches, raises, fights and exchanges monsters, and is very popular all over Japan. Of course, in my class. That's why I also raise monsters so that I can play with everyone in this game, but sadly there is no opponent to play against. I'm not the type who is good at talking to people positively. So today, I'm lonely raising the level of the monster while waiting for my classmates to invite me.

And finally, the long-awaited moment has arrived. One of my classmates asked me if I could play. She proudly showed her monsters.

The general packet monster battle rule is that each player prepares N monsters and fights one against each other. Each monster has a number called "level" that indicates the degree of growth, and the monster with the higher level always wins. At the same level, it is a draw. Once a monster has fought, it cannot be made to fight any further. After N one-on-one battles, the winner is the player who wins the majority.

The moment I saw her monster, I had a bad feeling. All her monsters look very strong. You can lose if you fight me. However, if I lose too badly, I think "it's not fun to fight this guy" and I think he won't play anymore. I hate it very much. So
"Sorry, I don't have N monsters yet."

I lied.

Even if you don't win in the N rounds, you may win if you have a special rule to play with a smaller number of monsters. I said earlier that it's okay to lose, but I'm glad if I win.

She accepted this special rule. In other words, the winner is the one who chooses k of each other's monsters and fights them one by one in turn, and wins the majority (that is, the number larger than k / 2).

Earlier I knew the level of her monster. I don't know which monster she chooses and in what order. But if I decide how many monsters to play against, I may be able to win no matter what choice she makes.

I would like to ask everyone. Enter the number of monsters N and the level of the monsters they have, and write a program that outputs the minimum number of monsters k that I can win no matter what choice she makes.

input

The input consists of multiple datasets. The end of the input is indicated by a single zero line. Each dataset is given in the following format:

N
a1 a2 ... aN
b1 b2 ... bN

The number of monsters N (1 ≤ N ≤ 40000) is given on the first line. On the second line, your monster's level ai (1 ≤ ai ≤ 100000) is given with one blank delimiter. On the third line, the level bi (1 ≤ bi ≤ 100000) of the classmate monster is given with one blank delimiter.

The number of datasets does not exceed 50.

output

For each data set, if k (1 ≤ k <N) exists, the minimum value is output on one line. If k does not exist or k is equal to N, then NA is output.

Example

Input

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

Output

3
1
NA

```python
from collections import deque
while True:
    n = int(input())
    if n == 0:break
    q1 = deque(sorted(map(int, input().split())))
    q2 = deque(sorted(map(int, input().split())))
    cnt = 0
    for k in range(1, n):
        top1 = q1.pop()
        top2 = q2.pop()
        if top1 > top2:
            cnt += 1
            q2.append(top2)
            q2.popleft()
            if cnt * 2 > k:
                print(k)
                break
    else:
        print("NA")

```


p00454 Paint Color

problem

Information I want to paint a rectangular veneer board to make a signboard for the promotion of the Olympic Games. Some rectangular masking tapes are pre-attached to the veneer board where I do not want to paint. We decided to paint each area with a different color. For example, in the case of Figure 5-1 we use 5 colors of paint.

<image>

Create a program to find the number of paint colors to use when given the position to apply masking tape as input. However, the entire veneer board is not covered with masking tape, and all sides of the masking tape are on any of the veneer boards. Parallel to that side.

input

The input consists of multiple datasets. Each dataset is given in the following format.

On the first line, the width w (integer with 1 ≤ w ≤ 1000000) and height h (integer with 1 ≤ h ≤ 1000000) are written in this order, separated by blanks.

The number of masking tapes n (an integer such that 1 ≤ n ≤ 1000) is written on the second line. The second and subsequent lines 2 + i (1 ≤ i ≤ n) are the i-th. The lower left coordinates (x1, y1) and the upper right coordinates (x2, y2) of the masking tape to be applied are x1, y1, x2, y2 (0 ≤ x1 <x2 ≤ w, 0 ≤ y1 <y2 ≤ h) It is written in the order of, separated by blanks.

However, the coordinates of the lower left corner of the plywood are (0, 0) and the coordinates of the upper right corner are (w, h). Of the scoring data, 30% of the points are w ≤ 100, h ≤ 100, n ≤ 100.

<image>

When both h and w are 0, it indicates the end of input. The number of data sets does not exceed 20.

output

Outputs the number of paint colors used for each dataset on one line.

Examples

Input

15 6
10
1 4 5 6
2 1 4 5
1 0 5 1
6 1 7 5
7 5 9 6
7 0 9 2
9 1 10 5
11 0 14 1
12 1 13 5
11 5 14 6
0 0

Output

5

Input

None

Output

None

```python
# -*- coding: utf-8 -*-
from typing import Union, List
import io, sys
import bisect
from collections import deque

def main():
    w,h = list(map(int, sys.stdin.readline().split()))

    if w == h == 0:
        return "END"

    n = int( sys.stdin.readline() )
    x1y1x2y2_list = [ list(map(int, sys.stdin.readline().split())) for _ in range(n) ]

    X1,Y1,X2,Y2 = list(map(list, zip(*x1y1x2y2_list)))

    all_X = compress(X1,X2,w)
    all_Y = compress(Y1,Y2,h)

    matrix =[ [0]*len(all_X) for _ in range(len(all_Y)) ]

    for i in range(n):
        matrix[ Y1[i] ][ X1[i] ] += 1
        matrix[ Y2[i] ][ X2[i] ] += 1
        matrix[ Y2[i] ][ X1[i] ] -= 1
        matrix[ Y1[i] ][ X2[i] ] -= 1

    for row in range(len(matrix)):
        for col in range(1, len(matrix[0])):
            matrix[row][col] += matrix[row][col-1]

    for row in range(1, len(matrix)):
        for col in range(len(matrix[0])):
            matrix[row][col] += matrix[row-1][col]

    del matrix[-1]

    for row in range(len(matrix)):
        del matrix[row][-1]

    cnt = 0

    for row in range(len(matrix)):
        for col in range(len(matrix[0])):
            if matrix[row][col] == 0:
                cnt += 1
                bfs_paint(matrix, col, row, cnt)

    print(cnt)

def compress(A1 :list, A2 :list, max_A):
    all_A = []
    #delta = [-1, 0, 1]
    delta = [0]

    for a in (A1 + A2):
        for d in delta:
            val = a + d

            if 0 <= val <= max_A:
                all_A.append(a + d)

    all_A += [0, max_A]
    all_A = sorted(set(all_A))

    for i in range(len(A1)):
        A1[i] = bisect.bisect_left(all_A, A1[i])
        A2[i] = bisect.bisect_left(all_A, A2[i])

    return all_A

def bfs_paint(matrix :List[list], col :int, row :int, cnt :int):
    queue = deque([ (col, row) ])
    matrix[row][col] = cnt
    delta = [(0,1),(0,-1),(1,0),(-1,0)]  # (column, row)

    while queue:
        c,r = queue.popleft()

        for d in delta:
            next_c = c + d[0]
            next_r = r + d[1]

            if (0 <= next_c < len(matrix[0])) and (0 <= next_r < len(matrix)) and \
                matrix[next_r][next_c] == 0:

                matrix[next_r][next_c] = cnt
                queue.append( (next_c, next_r) )

if __name__ == "__main__":
    while True:
        ret = main()

        if ret == "END":
            break

```


p00789 Square Coins

People in Silverland use square coins. Not only they have square shapes but also their values are square numbers. Coins with values of all square numbers up to 289 (= 172), i.e., 1-credit coins, 4-credit coins, 9-credit coins, ..., and 289-credit coins, are available in Silverland.

There are four combinations of coins to pay ten credits:

* ten 1-credit coins,
* one 4-credit coin and six 1-credit coins,
* two 4-credit coins and two 1-credit coins, and
* one 9-credit coin and one 1-credit coin.

Your mission is to count the number of ways to pay a given amount using coins of Silverland.

Input

The input consists of lines each containing an integer meaning an amount to be paid, followed by a line containing a zero. You may assume that all the amounts are positive and less than 300.

Output

For each of the given amount, one line containing a single integer representing the number of combinations of coins should be output. No other characters should appear in the output.

Example

Input

2
10
30
0

Output

1
4
27

```python
# AOJ 1209: Square Coins
#Python3 2018.7.19 bal4u

dp = [1]*300
for i in range(2, 18):
    for j in range(i**2, 300): dp[j] += dp[j-i**2]

while True:
    n = int(input())
    if n == 0: break
    print(dp[n])

```


p00921 Don't Burst the Balloon

An open-top box having a square bottom is placed on the floor. You see a number of needles vertically planted on its bottom.

You want to place a largest possible spheric balloon touching the box bottom, interfering with none of the side walls nor the needles.

Java Specific: Submitted Java programs may not use "java.awt.geom.Area". You may use it for your debugging purposes.

Figure H.1 shows an example of a box with needles and the corresponding largest spheric balloon. It corresponds to the first dataset of the sample input below.

<image>
Figure H.1. The upper shows an example layout and the lower shows the largest spheric balloon that can be placed.

Input

The input is a sequence of datasets. Each dataset is formatted as follows.

n w
x1 y1 h1
:
xn yn hn

The first line of a dataset contains two positive integers, n and w, separated by a space. n represents the number of needles, and w represents the height of the side walls.

The bottom of the box is a 100 × 100 square. The corners of the bottom face are placed at positions (0, 0, 0), (0, 100, 0), (100, 100, 0), and (100, 0, 0).

Each of the n lines following the first line contains three integers, xi, yi, and hi. (xi, yi, 0) and hi represent the base position and the height of the i-th needle. No two needles stand at the same position.

You can assume that 1 ≤ n ≤ 10, 10 ≤ w ≤ 200, 0 < xi < 100, 0 < yi < 100 and 1 ≤ hi ≤ 200. You can ignore the thicknesses of the needles and the walls.

The end of the input is indicated by a line of two zeros. The number of datasets does not exceed 1000.

Output

For each dataset, output a single line containing the maximum radius of a balloon that can touch the bottom of the box without interfering with the side walls or the needles. The output should not contain an error greater than 0.0001.

Example

Input

5 16
70 66 40
38 52 20
40 35 10
70 30 10
20 60 10
1 100
54 75 200
1 10
90 10 1
1 11
54 75 200
3 10
53 60 1
61 38 1
45 48 1
4 10
20 20 10
20 80 10
80 20 10
80 80 10
0 0

Output

26.00000
39.00000
130.00000
49.49777
85.00000
95.00000


p01054 String Conversion

Problem

Jennifer and Marian presented Carla with the string S.
However, Carla is not happy to receive the string S.
I wanted the string T.
The three decided to work together to change the string S to the string T.

Jennifer first sorts the letters in any order.

Marian then exchanges the lowercase letters of the two alphabets any number of times.
This operation exchanges all the same characters in the string, for example:

* aab-> Swap a and b-> bba
* aab-> Swap a and c-> ccb

Finally, Carla replaces one character with another and repeats until T.
Jennifer and Marian decided to try to reduce the number of Carla replacements.
Find the minimum number of replacements that Carla makes.

Constraints

* 1 ≤ n ≤ 105
* S and T contain only'a'~'z'
* | S | = | T | = n

Input

n
S
T

The length n of the string is given on the first line.
The character string S is given on the second line, and the character string T is given on the third line.

Output

Print the minimum number of Carla replacements on one line.

Examples

Input

3
abc
xyz

Output

0

Input

5
aaabb
xyxyz

Output

1

```python
# AOJ 1568: String Conversion
# Python3 2018.7.13 bal4u

cha, chzn = ord('a'), ord('z')+1
S, T = [0]*128, [0]*128
input()
a = input()
for x in a: S[ord(x)] += 1
S = sorted(S[cha:chzn], reverse=True)
a = input()
for x in a: T[ord(x)] += 1
T = sorted(T[cha:chzn], reverse=True)
ans = 0
for i in range(26): ans += abs(S[i]-T[i])
print(ans >> 1)

```


p01323 Compile

Masa Kita, who entered the University of Tokyo, joined a circle called TSG (University of Tokyo Super Gamers).

This circle exhibits games at the Komaba Festival every year, and Masa Kita decided to create and display the games as well.

The game created by Kitamasa is a common falling block puzzle game such as the following.

* There is a grid-like field of 6 squares x 12 squares, and one block can be placed for each square.
* Two blocks fall from the top in pairs. There are a total of 6 types of blocks, including basic blocks in 5 colors of red, green, blue, yellow, and purple, and obstructive blocks. The player can change the drop position by rotating and laterally moving the block.
* When a falling block collides with the floor of the field or another block, the block is fixed at that position.
* If there are blocks of the same color as the fixed block in four directions around them, they will stick to each other. However, the disturbing blocks do not stick to each other.
* If 4 or more blocks stick together, it will disappear and you will get a score. When the basic blocks that exist in the four directions around the disturbing block disappear, the disturbing block also disappears. The disappearance of blocks occurs at the same time when all the blocks have finished falling.
* When a block disappears, the block above it will fall. The player cannot control the fall of this block. At this time, if four or more blocks stick together again, they disappear and a chain occurs. However, even if multiple colors are erased at the same time, it will be treated as one chain.

Kitamasa finished writing most of the programs for this game, but couldn't write what to do when the blocks stuck together and disappeared. So I decided to ask a friend of the circle to write the program for that part.

Notes on Test Cases

Multiple datasets are given in the above input format.

The first line of input is given the number T of the dataset.

Create a program that outputs each data set in the above output format.

<!-

Input

The input consists of 12 lines.

The i-th line of the input consists of a character string of length 6, and the j-th character represents the state of the cells in the i-th line from the top of the field and the j-th column from the left.

The character that represents the state of the square is one of the following seven.

Character | Type
--- | ---
R | red
G | green
B | blue
Y | yellow
P | Purple
O | disturb
. | Empty space

Also, all blocks included in the input are on the floor or on other blocks.

Output

From the input state, calculate the number of chains when the blocks are erased according to the rules, and output in one line.

If none of the blocks disappear, output 0.

Examples

Input

3
......
......
......
......
......
......
......
......
.RGB..
RGOP..
RGBPB.
RGBPP.
GBRGYP
GBRRYP
BGGRBB
BPRGYY
GGPRRY
BYPPRB
YGGGPB
GYYYPR
YRBRBR
YBRBRB
BRBRBR
BRBRBR
......
......
......
......
......
......
......
......
......
......
..OO..
..OO..

Output

3
18
0

Input

......
......
......
......
......
......
......
......
.RGB..
RGOP..
RGBPB.
RGBPP.

Output

3

Input

GBRGYP
GBRRYP
BGGRBB
BPRGYY
GGPRRY
BYPPRB
YGGGPB
GYYYPR
YRBRBR
YBRBRB
BRBRBR
BRBRBR

Output

18

Input

......
......
......
......
......
......
......
......
......
......
..OO..
..OO..

Output

0


p01491 RabbitLunch

Example

Input

2 3 1 3 1 0

Output

2

```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
    M, N, m0, md, n0, nd = map(int, readline().split())

    S = [0]*(M+1)
    S[0] = mi = m0
    for i in range(1, M):
        S[i] = mi = (mi * 58 + md) % (N + 1)
    S.sort()
    for i in range(M):
        S[i+1] += S[i]

    T = [0]*(N+1)
    T[0] = ni = n0
    for i in range(1, N):
        T[i] = ni = (ni * 58 + nd) % (M + 1)
    T.sort()
    for i in range(N):
        T[i+1] += T[i]

    def gen():
        def calc(a, b):
            return (M - a)*(N - b) + S[a] + T[b]
        yield 10**18
        j = N
        for i in range(M+1):
            while j > 0 and calc(i, j) > calc(i, j-1):
                j -= 1
            yield calc(i, j)
    write("%d\n" % min(gen()))
solve()

```