374_A. Inna and Pink Pony

Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b.

Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types:

  * move the candy from position (x, y) on the board to position (x - a, y - b);
  * move the candy from position (x, y) on the board to position (x + a, y - b);
  * move the candy from position (x, y) on the board to position (x - a, y + b);
  * move the candy from position (x, y) on the board to position (x + a, y + b).

Naturally, Dima doesn't allow to move the candy beyond the chessboard borders.

Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (i, j) to one of the chessboard corners. Help them cope with the task!

Input

The first line of the input contains six integers n, m, i, j, a, b (1 ≤ n, m ≤ 106; 1 ≤ i ≤ n; 1 ≤ j ≤ m; 1 ≤ a, b ≤ 106).

You can assume that the chessboard rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. Position (i, j) in the statement is a chessboard cell on the intersection of the i-th row and the j-th column. You can consider that the corners are: (1, m), (n, 1), (n, m), (1, 1).

Output

In a single line print a single integer — the minimum number of moves needed to get the candy.

If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes.

Examples

Input

5 7 1 3 2 2

Output

2

Input

5 5 2 3 1 1

Output

Poor Inna and pony!

Note

Note to sample 1:

Inna and the pony can move the candy to position (1 + 2, 3 + 2) = (3, 5), from there they can move it to positions (3 - 2, 5 + 2) = (1, 7) and (3 + 2, 5 + 2) = (5, 7). These positions correspond to the corner squares of the chess board. Thus, the answer to the test sample equals two.

```python
n, m, i, j, a, b = map(int, input().split())
corners = [(1, 1), (1, m), (n, 1), (n, m)]
result = False
ans = -1
for cnt in corners:
    if (abs(cnt[0] - i) % a == 0) and (abs(cnt[1] - j) % b == 0):
        result = True
        t1, t2 = abs(cnt[0] - i) // a, abs(cnt[1] - j) // b
        if (t1 + t2) % 2 == 0:
            if ans == -1:
                ans = max(abs(cnt[0] - i) // a, abs(cnt[1] - j) // b)
            else:
                ans = min(max(abs(cnt[0] - i) // a, abs(cnt[1] - j) // b), ans)
if ans == 0:
    print(ans)
elif not result or (i+a > n and i-a < 1) or (j+b > m and j-b < 1) or ans == -1:
    print("Poor Inna and pony!")
else:
    print(ans)
```


445_B. DZY Loves Chemistry

DZY loves chemistry, and he enjoys mixing chemicals.

DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.

Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.

Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

Input

The first line contains two space-separated integers n and m <image>.

Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input.

Consider all the chemicals numbered from 1 to n in some order.

Output

Print a single integer — the maximum possible danger.

Examples

Input

1 0

Output

1

Input

2 1
1 2

Output

2

Input

3 2
1 2
2 3

Output

4

Note

In the first sample, there's only one way to pour, and the danger won't increase.

In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.

In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).

```python
def iterative_dfs(graph, start, path=[]):
    visited = {}
    for i in graph:
        visited[i] = []
    q=[start]
    while q:
        v=q.pop(0)
        if not visited[v]:
            visited[v] = True
            path=path+[v]
            q=graph[v]+q
    return path

nodes, edges = map(int, input().split(' '))
graph = {}
for i in range(nodes):
  graph[i] = []

for i in range(edges):
  a, b = map(int, input().split(' '))
  graph[a-1].append(b-1)
  graph[b-1].append(a-1)

marked = [False] * nodes
num = 0
for i in range(nodes):
  if not marked[i]:
    for j in iterative_dfs(graph, i):
      marked[j] = True
    num += 1
print(2**(nodes-num))

```


467_C. George and Job

The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.

Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers:

[l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m),

in such a way that the value of sum <image> is maximal possible. Help George to cope with the task.

Input

The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109).

Output

Print an integer in a single line — the maximum possible value of sum.

Examples

Input

5 2 1
1 2 3 4 5

Output

9

Input

7 1 3
2 10 7 18 5 33 0

Output

61

```python
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
p_a = [0 for _ in range(n)]
p_a[0] = a[0]
for i in range(1, n):
    p_a[i] = p_a[i - 1] + a[i]
INF = -1e10
# print(p_a)
dp = {}

from types import GeneratorType

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

    return wrappedfunc
@bootstrap
def solve(i, k, m):
    if (i, k, m) in dp:
        yield dp[(i, k, m)]
    if k == 0:
        dp[(i, k, m)] = 0
        yield 0
    if i + m == n:
        if k == 1:
            # print(p_a[n - 1] - p_a[i - 1])
            if i==0:
                dp[(i, k, m)]=p_a[n - 1]
            else:
                dp[(i, k, m)] = p_a[n - 1] - p_a[i - 1]
            yield dp[(i, k, m)]
        if k > 1:
            dp[(i, k, m)] = INF
            yield INF

    if i + m > n - 1:
        dp[(i, k, m)] = INF
        yield INF

    if k == 0:
        dp[(i, k, m)] = 0
        yield 0
    if i == 0:
        a=yield solve(i + 1, k, m)
        b=yield solve(i + m, k - 1, m)
        dp[(i, k, m)] = max(a ,b+ p_a[i + m - 1])
        yield dp[(i, k, m)]
    else:
        a = yield solve(i + 1, k, m)
        b=yield solve(i + m, k - 1, m)
        dp[(i, k, m)] = max(a, b+ p_a[i + m - 1] - p_a[i - 1])
        yield dp[(i, k, m)]

if m==1:print(sum(sorted(a)[n-k:]))
else:
    print(solve(0, k, m))

```


513_G1. Inversions problem

You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.

Input

The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.

The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.

  * In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
  * In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
  * In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.

Output

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

Examples

Input

3 1
1 2 3

Output

0.833333333333333

Input

3 4
1 3 2

Output

1.458333333333334

Note

Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.

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

def count_invs(a):
    ans = 0
    for i in range(n-1):
        for j in range(i + 1, n):
            if a[i] > a[j]:
                ans += 1
    return ans

def inv_in_perms(a, count):
    if count > 0:
        ans = 0
        for l in range(n):
            for r in range(l, n):
                a[l: r + 1] = a[l: r + 1][::-1]
                ans += inv_in_perms(a, count - 1)
                a[l: r + 1] = a[l: r + 1][::-1]
        return(ans)
    else:
        return(count_invs(a))

total = (n * (n + 1) // 2) ** k
perms = 0

print(inv_in_perms(p, k) / total)
```


53_D. Physical Education

Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.

Input

The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.

Output

In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.

Examples

Input

4
1 2 3 2
3 2 1 2

Output

4
2 3
1 2
3 4
2 3

Input

2
1 100500
1 100500

Output

0

```python
import sys

n = int(sys.stdin.readline ())
a= [int (x) for x in sys.stdin.readline ().split ()]
assert len(a) == n

b = [int (x) for x in sys.stdin.readline ().split ()]
assert len(b) == n

ans = []

for i in range (n):
    j = i;
    while b[j] != a[i] :
        j += 1
    while j > i:
        ans += [(j, j + 1)]
        b[j - 1], b[j] = b[j], b[j - 1]
        j -= 1
print (len(ans))
for p, q in ans:
    print (p, + q)
```


567_F. Mausoleum

King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.

The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.

The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:

  * [1, 2, 2, 3, 4, 4, 3, 1];
  * [1, 1];
  * [2, 2, 1, 1];
  * [1, 2, 3, 3, 2, 1].

Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.

Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.

Input

The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.

Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.

Output

Print the sought number of ways.

Examples

Input

3 0

Output

9

Input

3 1
2 > 3

Output

1

Input

4 1
3 = 6

Output

3

```python
n,k = map(int,input().split())
n*=2
n+=2
l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n
ok = 1
for i in range(k):
    a,c,b = input().split()
    a,b = int(a), int(b)
    if c=="=":
        if a==b:
            continue
        if (e[a] and e[a]!=b) or (e[b] and e[b]!=a):
             ok = 0
        e[a], e[b] = b,a
    if c=="<":
        a,b,c = b,a,">"
    if c==">":
        l[a].append(b)
    if c=="<=":
        a,b,c = b,a,">="
    if c==">=":
        le[a].append(b)

def check(i, j, a, b):
    if e[a] and e[a]!=a and e[a]!=b:
        return 0
    for x in l[a]:
        if x>i and x<j:
            return 0
    for x in le[a]:
        if x>i and x<j and x!=a and x!=b:
            return 0
    return 1

dp = [[0]*n for i in range(n)]
dp[0][n-1] = 1
ans = 0
for i in range(n):
    for j in range(n-1,i,-1):
        if i+1==j:
            ans+=dp[i][j]
        elif ((i+j)%2)==1:
            if check(i,j,i+1,i+2) and check(i,j,i+2,i+1):
                dp[i+2][j]+=dp[i][j]
            if i+3<j and check(i,j,j-2,j-1) and check(i,j,j-1,j-2):
                dp[i][j-2]+=dp[i][j]
            if i+3<j and check(i,j,i+1,j-1) and check(i,j,j-1,i+1):
                dp[i+1][j-1]+=dp[i][j]

print(ans if ok else 0)
```


630_O. Arrow

Petya has recently started working as a programmer in the IT city company that develops computer games.

Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.

A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.

The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.

Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.

<image>

Input

The only line of the input contains eight integers px, py, vx, vy ( - 1000 ≤ px, py, vx, vy ≤ 1000, vx2 + vy2 > 0), a, b, c, d (1 ≤ a, b, c, d ≤ 1000, a > c).

Output

Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10 - 9.

Examples

Input

8 8 0 2 8 3 4 5

Output

8.000000000000 11.000000000000
4.000000000000 8.000000000000
6.000000000000 8.000000000000
6.000000000000 3.000000000000
10.000000000000 3.000000000000
10.000000000000 8.000000000000
12.000000000000 8.000000000000

```python
from math import atan2, pi

EPS = 0.00000001

def eq(a, b):
    return abs(a - b) < EPS

class Vector:
    def __init__(self, x2, y2, x1=0, y1=0):
        self.x = (x2 - x1)
        self.y = y2 - y1
        self.s = (self.x ** 2 + self.y ** 2) ** 0.5

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    def mul_k(self, k):
        self.x *= k
        self.y *= k

    def mul_kk(self, k):
        return Vector(self.x * k, self.y * k)

    def rotate(self):
        return Vector(-self.y, self.x)

    def rotate2(self):
        return self.rotate().rotate().rotate()

    def reverseee(self):
        return Vector(-self.x, -self.y)

    def __mul__(self, other):
        return self.x * other.x + self.y * other.y

    def vectormul(self, other):
        return self.x * other.y - self.y * other.x

    def get_angle(self, other):
        return atan2(self.vectormul(other), self * other)

    def norm(self):
        if self.s == 0:
            return Vector(self.x, self.y)
        return Vector(self.x / self.s, self.y / self.s)

    def __str__(self):
        return f'{self.x} {self.y}'

    def middle(self, point):
        return Vector((self.x + point.x) / 2, (self.y + point.y) / 2)

class Line:
    def __init__(self, point=None, vector=None, point2=None, a=None, b=None, c=None):
        if a is not None:
            self.v = Vector(a, b).rotate()
            self.p = Vector(a, b)
            self.p.mul_k(-c / (a ** 2 + b ** 2))
            self.A = a
            self.B = b
            self.C = c
            return
        if vector is None:
            vector = point2 - point
        self.p = point
        self.v = vector
        self.A = self.v.y
        self.B = -self.v.x
        self.C = - self.A * self.p.x - self.p.y * self.B

    def get_abc(self):
        return self.A, self.B, self.C

    def __str__(self):
        return str(self.A) + ' ' + str(self.B) + ' ' + str(self.C)

    def check(self, point):
        return eq(- point.x * self.A - self.B * point.y, self.C)

    def get_s_from_point(self, point):
        v = self.v.norm()
        v2 = point - self.p
        a = v * v2
        v.mul_k(a)
        v3 = v + self.p
        s = v3 - point
        return s.s

    def get_bisect(self, line):
        return Line(point=self.get_peresech(line)[1], vector=self.v.norm() + line.v.norm())

    def get_proection(self, point):
        v = self.v.norm()
        v2 = point - self.p
        a = v * v2
        v.mul_k(a)
        v3 = v + self.p
        return v3

    def get_paral_line(self, le):
        v = self.v.norm().rotate()
        v.mul_k(le)
        return Line(point=self.p + v, vector=self.v)

    def get_peresech(self, lin):
        u = lin.v.rotate()
        a = self.v * u
        if eq(a, 0):
            if eq(self.get_s_from_point(lin.p), 0):
                return (2,)
            return (0,)
        t = ((lin.p - self.p) * u) / (self.v * u)
        v = Vector(self.v.x, self.v.y)
        v.mul_k(t)
        return (1, self.p + v)

    def get_mirror(self, point):
        v = self.v.norm()
        v2 = point - self.p
        a = v * v2
        v.mul_k(a)
        v3 = v + self.p
        s = v3 - point
        return s + v3

def is_on_line(v1, v2):
    return eq(v1.vectormul(v2), 0)

def is_on_luch(v1, v2):
    return eq(v1.get_angle(v2), 0)

def is_on_otr(v1, v2, v3, v4):
    return eq(v1.get_angle(v2), 0) and eq(v3.get_angle(v4), 0)

def get_s_from_luch(xp, yp, x1, y1, x2, y2):
    v = Vector(x2, y2, x1, y1).norm()
    v2 = Vector(xp, yp, x1, y1)
    a = v * v2
    v1 = Vector(x2, y2, x1, y1)
    v.mul_k(a)
    v3 = v + Vector(x1, y1)
    xh, yh = v3.x, v3.y
    v4 = Vector(xh, yh, x1, y1)
    b = v1.get_angle(v4)
    if eq(b, 0):
        se = v3 - Vector(xp, yp)
        return se.s
    else:
        return (Vector(x1, y1) - Vector(xp, yp)).s

def get_s_from_otr(xp, yp, x1, y1, x2, y2):
    return max(get_s_from_luch(xp, yp, x1, y1, x2, y2), get_s_from_luch(xp, yp, x2, y2, x1, y1))

def get_s_from_line(xp, yp, x1, y1, x2, y2):
    v = Vector(x2, y2, x1, y1).norm()
    v2 = Vector(xp, yp, x1, y1)
    a = v * v2
    return a

def peresec_otr(x1, y1, x2, y2, x3, y3, x4, y4):
    AB = Vector(x2, y2, x1, y1)
    CD = Vector(x4, y4, x3, y3)
    AC = Vector(x3, y3, x1, y1)
    AD = Vector(x4, y4, x1, y1)
    CA = Vector(x1, y1, x3, y3)
    CB = Vector(x2, y2, x3, y3)
    yg1 = AB.get_angle(AD)
    yg2 = AB.get_angle(AC)
    yg3 = CD.get_angle(CA)
    yg4 = CD.get_angle(CB)
    flag = False
    if (yg1 < 0 and yg2 < 0) or (yg1 > 0 and yg2 > 0):
        flag = True
    if (yg3 < 0 and yg4 < 0) or (yg3 > 0 and yg4 > 0):
        flag = True
    if max(min(x1, x2), min(x3, x4)) > min(max(x1, x2), max(x3, x4)):
        flag = True
    if max(min(y1, y2), min(y3, y4)) > min(max(y1, y2), max(y3, y4)):
        flag = True
    return not flag

def get_s_from_otr_to_otr(x1, y1, x2, y2, x3, y3, x4, y4):
    if peresec_otr(x1, y1, x2, y2, x3, y3, x4, y4):
        return 0
    return min(get_s_from_otr(x1, y1, x3, y3, x4, y4), get_s_from_otr(x2, y2, x3, y3, x4, y4),
               get_s_from_otr(x3, y3, x1, y1, x2, y2), get_s_from_otr(x4, y4, x1, y1, x2, y2))

def main():
    px, py, vx, vy, a, b, c, d = map(int, input().split())
    P = Vector(px, py)
    V = Vector(vx, vy).norm()
    A = V.mul_kk(b) + P
    B = V.mul_kk(a/2).rotate() + P
    C = V.mul_kk(c/2).rotate() + P
    D = C + V.rotate().rotate().mul_kk(d)
    E = D + V.rotate2().mul_kk(c)
    F = P + V.rotate2().mul_kk(c/2)
    G = P + V.rotate2().mul_kk(a/2)
    print(A, B, C, D, E, F, G, sep='\n')

main()

```


659_G. Fence Divercity

Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.

Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).

You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.

As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).

Input

The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence.

The second line contains n space-separated numbers h1, h2, ..., hn (1 ≤ hi ≤ 109), where hi equals the height of the i-th board to the left.

Output

Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.

Examples

Input

2
1 1

Output

0

Input

3
3 4 2

Output

13

Note

From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.

All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):

<image>

```python
mod = 10 ** 9 + 7
n = int(input())
h = list(map(lambda x: int(x) - 1, input().split()))
ans = x = 0
for i in range(n):
    ans += h[i] + min(h[i], h[i - 1]) * x
    if i < n - 1:
        x *= min(h[i - 1], h[i], h[i + 1])
        x += min(h[i], h[i + 1])
    ans %= mod
    x %= mod
print(ans)

```


682_D. Alyona and Strings

After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.

Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants.

Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions:

  * s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty);
  * t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty);
  * sum of the lengths of strings in sequence is maximum possible.

Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.

A substring of a string is a subsequence of consecutive characters of the string.

Input

In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively.

The second line of the input contains string s, consisting of lowercase English letters.

The third line of the input contains string t, consisting of lowercase English letters.

Output

In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence.

It is guaranteed, that at least one desired sequence exists.

Examples

Input

3 2 2
abc
ab

Output

2

Input

9 12 4
bbaaababb
abbbabbaaaba

Output

7

Note

The following image describes the answer for the second sample case:

<image>

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

n += 1
m += 1

p = [i for i in range(n * m - n) if (i + 1) % n]
r = p[::-1]

d = [0] * n * m

for i in p:
    if s[i % n] == t[i // n]: d[i] = d[i - n - 1] + 1

f = d[:]

for y in range(k - 1):
    for i in p: f[i] = max(f[i], f[i - 1], f[i - n])
    for i in r: f[i] = f[i - d[i] * (n + 1)] + d[i]

print(max(f))
```


705_C. 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
import collections
import copy

n, q = map(int, input().split())
Q = collections.deque()
A = n * [0]
B = copy.copy(A)
L = []
s = n = 0
for _ in range(q):
    y, x = map(int, input().split())
    if 2 > y:
        x -= 1
        Q.append(x)
        B[x] += 1
        A[x] += 1
        s += 1
    elif 3 > y:
        x -= 1
        s -= A[x]
        A[x] = 0
    else:
        while x > n:
            n += 1
            y = Q.popleft()
            B[y] -= 1
            if B[y] < A[y]:
                A[y] -= 1
                s -= 1
    L.append(str(s))
print('\n'.join(L))

```


749_A. Bachgold Problem

Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.

Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.

Input

The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).

Output

The first line of the output contains a single integer k — maximum possible number of primes in representation.

The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.

Examples

Input

5

Output

2
2 3

Input

6

Output

3
2 2 2

```python
n=int(input())
c=0
if(n%2==1):
    n-=3
    l=[2]*(n//2)
    l.append(3)
    print(len(l))
    print(*l)
else:
    l=[2]*(n//2)
    print(len(l))
    print(*l)
```


817_B. Makes And The Product

After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!

Input

The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.

Output

Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.

Examples

Input

4
1 1 1 1

Output

4

Input

5
1 3 2 3 4

Output

2

Input

6
1 3 3 1 3 2

Output

1

Note

In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.

In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.

In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.


842_B. Gleb And Pizza

Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.

The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).

Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

Input

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust.

Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105).

Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.

Output

Output the number of pieces of sausage that lay on the crust.

Examples

Input

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

Output

2

Input

10 8
4
0 0 9
0 0 10
1 0 1
1 0 2

Output

0

Note

Below is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

<image>


863_B. Kayaking

Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.

Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is wi, and weight is an important matter in kayaking — if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.

Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.

Help the party to determine minimum possible total instability!

Input

The first line contains one number n (2 ≤ n ≤ 50).

The second line contains 2·n integer numbers w1, w2, ..., w2n, where wi is weight of person i (1 ≤ wi ≤ 1000).

Output

Print minimum possible total instability.

Examples

Input

2
1 2 3 4

Output

1

Input

4
1 3 4 6 3 4 100 200

Output

5

```python
n = int(input())
n = 2*n
w = [int(i) for i in input().split()]
w.sort()

import math
res = math.inf
for x in range(n):
  for y in range(x+1, n):
      wc = w[:]
      wc.pop(y); wc.pop(x)
      # print(wc)
      s = 0
      for i in range(0, n-3, 2):
        s += wc[i+1]-wc[i]
      res = min(s, res)
print(res)
```


888_F. Connecting Vertices

There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly).

But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).

How many ways are there to connect all vertices with n - 1 segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo 109 + 7.

Input

The first line contains one number n (3 ≤ n ≤ 500) — the number of marked points.

Then n lines follow, each containing n elements. ai, j (j-th element of line i) is equal to 1 iff you can connect points i and j directly (otherwise ai, j = 0). It is guaranteed that for any pair of points ai, j = aj, i, and for any point ai, i = 0.

Output

Print the number of ways to connect points modulo 109 + 7.

Examples

Input

3
0 0 1
0 0 1
1 1 0

Output

1

Input

4
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

Output

12

Input

3
0 0 0
0 0 1
0 1 0

Output

0

```python
import sys
from array import array

n = int(input())
edge = [list(map(int, input().split())) for _ in range(n)]
mod = 10**9 + 7

dp_f = [array('i', [-1])*n for _ in range(n)]
dp_g = [array('i', [-1])*n for _ in range(n)]

for i in range(n):
    dp_f[i][i] = dp_g[i][i] = 1
for i in range(n-1):
    dp_f[i][i+1] = dp_g[i][i+1] = 1 if edge[i][i+1] else 0

def f(l, r):
    if dp_f[l][r] != -1:
        return dp_f[l][r]

    dp_f[l][r] = g(l, r) if edge[l][r] else 0
    for m in range(l+1, r):
        if edge[l][m]:
            dp_f[l][r] = (dp_f[l][r] + g(l, m) * f(m, r)) % mod

    return dp_f[l][r]

def g(l, r):
    if dp_g[l][r] != -1:
        return dp_g[l][r]

    dp_g[l][r] = f(l+1, r)
    for m in range(l+1, r):
        dp_g[l][r] = (dp_g[l][r] + f(l, m) * f(m+1, r)) % mod

    return dp_g[l][r]

print(f(0, n-1))
```


911_D. Inversion Counting

A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).

You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].

After each query you have to determine whether the number of inversions is odd or even.

Input

The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.

The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.

Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.

Output

Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.

Examples

Input

3
1 2 3
2
1 2
2 3

Output

odd
even

Input

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

Output

odd
odd
odd
even

Note

The first example:

  1. after the first query a = [2, 1, 3], inversion: (2, 1);
  2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).

The second example:

  1. a = [1, 2, 4, 3], inversion: (4, 3);
  2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
  3. a = [1, 2, 4, 3], inversion: (4, 3);
  4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2).

```python
def solve():
    n=int(input())
    a=list(map(int,input().split()))
    cl=['odd','even']
    m=int(input())
    ans=True
    b=[]
    ap=b.append
    for i in range(n):
        for j in range(i):
            if a[j]>a[i]:
                ans=not ans

    for i in range(m):
        left,right=map(int,input().split())
        if ((right-left+1)//2)%2 == 1:
            ans=not ans
        ap(cl[ans])
    print('\n'.join(b))
solve()
```


933_B. A Determined Cleanup

In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.

Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...

Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients).

Input

The only line of input contains two space-separated integers p and k (1 ≤ p ≤ 1018, 2 ≤ k ≤ 2 000).

Output

If the polynomial does not exist, print a single integer -1, or output two lines otherwise.

In the first line print a non-negative integer d — the number of coefficients in the polynomial.

In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial <image> fulfilling the given requirements. Your output should satisfy 0 ≤ ai < k for all 0 ≤ i ≤ d - 1, and ad - 1 ≠ 0.

If there are many possible solutions, print any of them.

Examples

Input

46 2

Output

7
0 1 0 0 1 1 1

Input

2018 214

Output

3
92 205 1

Note

In the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)·(x + 2) + 46.

In the second example, f(x) = x2 + 205x + 92 = (x - 9)·(x + 214) + 2018.

```python
s = input()
# s = '46 2'

p, k = list(map(int, s.split()))

res = []
f = True
while p != 0:
    if f:
        n = p % k
        m = (p - n) // k
        f = False
    else:
        n = (-p) % k
        m = (p + n) // k
        f = True
    res.append(n)
    p = m

print(len(res))
print(' '.join(list(map(str, res))))
```


987_B. High School: Become Human

Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.

It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids.

One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers.

Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him.

Input

On the only line of input there are two integers x and y (1 ≤ x, y ≤ 10^{9}).

Output

If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes).

Examples

Input

5 8

Output

>

Input

10 3

Output

<

Input

6 6

Output

=

Note

In the first example 5^8 = 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 ⋅ 5 = 390625, and 8^5 = 8 ⋅ 8 ⋅ 8 ⋅ 8 ⋅ 8 = 32768. So you should print '>'.

In the second example 10^3 = 1000 < 3^{10} = 59049.

In the third example 6^6 = 46656 = 6^6.

```python
import math
x,y=map(lambda x:math.log(int(x))/int(x),input().split())
print('<=>'[(x>=y)+(x>y)])
```


p02588 AtCoder Grand Contest 047 - Integer Product

You are given N real values A_1, A_2, \ldots, A_N. Compute the number of pairs of indices (i, j) such that i < j and the product A_i \cdot A_j is integer.

Constraints

* 2 \leq N \leq 200\,000
* 0 < A_i < 10^4
* A_i is given with at most 9 digits after the decimal.

Input

Input is given from Standard Input in the following format.

N
A_1
A_2
\vdots
A_N

Output

Print the number of pairs with integer product A_i \cdot A_j (and i < j).

Examples

Input

5
7.5
2.4
17.000000001
17
16.000000000

Output

3

Input

11
0.9
1
1
1.25
2.30000
5
70
0.000000001
9999.999999999
0.999999999
1.000000001

Output

8

```python
import collections

N=int(input())
A=[]
PRECISION_DIGITS=9
cnt=collections.defaultdict(int)

for n in range(N):
	tmpA = float(input())
	tmpA = round(tmpA*10**PRECISION_DIGITS)
	#print(tmpA)

	five = 0
	two = 0
	while (tmpA % 2) == 0:
		two += 1
		tmpA //= 2
	while (tmpA % 5) == 0:
		five += 1
		tmpA //= 5

	# (10**9) -> (two,five)=(9,9)
	two -= PRECISION_DIGITS
	five -= PRECISION_DIGITS

	cnt[(two,five)]+=1

# print(cnt)
ans = 0
for t1, cnt1 in cnt.items():
	for t2, cnt2 in cnt.items():
		# 2**a(a>=0) and 5**b(b>=0) => integer
		if 0 <= t1[0]+t2[0] and 0 <= t1[1]+t2[1]:
			if t1 < t2:
				ans += int(cnt1*cnt2)
			elif t1 == t2:
				# same entry
				# Total number of combinations choose 2 items
				# nC2 = n*(n-1)/2
				ans += int((cnt1*(cnt2-1))/2)

print(ans)

```


p02719 AtCoder Beginner Contest 161 - Replacing Integer

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

* 0 ≤ N ≤ 10^{18}
* 1 ≤ K ≤ 10^{18}
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Examples

Input

7 4

Output

1

Input

2 6

Output

2

Input

1000000000000000000 1

Output

0

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

a=n%k
b=abs(k-a)
print(min(a,b))
```


p02848 AtCoder Beginner Contest 146 - ROT N

We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.

Shift each character of S by N in alphabetical order (see below), and print the resulting string.

We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` by 3 results in `B` (`Y` \to `Z` \to `A` \to `B`).

Constraints

* 0 \leq N \leq 26
* 1 \leq |S| \leq 10^4
* S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the string resulting from shifting each character of S by N in alphabetical order.

Examples

Input

2
ABCXYZ

Output

CDEZAB

Input

0
ABCXYZ

Output

ABCXYZ

Input

13
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Output

NOPQRSTUVWXYZABCDEFGHIJKLM

```python
N = int(input())
S = input()

print(''.join(chr((ord(c) - ord('A') + N) % 26 + ord('A')) for c in S))

```


p02986 AtCoder Beginner Contest 133 - Colorful Tree

There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.

Answer the following Q queries:

* Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)

Constraints

* 2 \leq N \leq 10^5
* 1 \leq Q \leq 10^5
* 1 \leq a_i, b_i \leq N
* 1 \leq c_i \leq N-1
* 1 \leq d_i \leq 10^4
* 1 \leq x_j \leq N-1
* 1 \leq y_j \leq 10^4
* 1 \leq u_j < v_j \leq N
* The given graph is a tree.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q

Output

Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.

Example

Input

5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4

Output

130
200
60

```python
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**9)
class LCA:
    def __init__(self,V,edges,depth,parent,root=0):
        self.edges=edges
        self.maxLog=18
        self.parent=[[-1]*V for _ in range(self.maxLog+1)]
        self.parent[0]=parent
        self.depth=depth
        for i in range(self.maxLog):
            for j in range(V):
                if self.parent[i][j]!=-1:
                    self.parent[i+1][j]=self.parent[i][self.parent[i][j]]
    def lca(self,a,b):
        if self.depth[a]>self.depth[b]:
            a,b=b,a
        for i in range(self.maxLog):
            if (self.depth[b]-self.depth[a])&(1<<i):
                b=self.parent[i][b]
        if a==b:
            return b
        for i in reversed(range(self.maxLog-1)):
            if self.parent[i][a]!=self.parent[i][b]:
                a=self.parent[i][a]
                b=self.parent[i][b]
        return self.parent[0][a]

from collections import deque
def Eulertour(Edges,n,root=0):
    Euler=[]
    Depth=[-1]*n
    Depth[root]=0
    Parent=[-1]*n
    que=deque([root])
    que2=deque()
    Visited=[False]*n
    while que:
        fr=que.pop()
        Euler.append((Depth[fr],fr))
        if Visited[fr]:
            continue
        for to in Edges[fr]:
            if Visited[to]:
                que.append(to)
            else:
                Depth[to]=Depth[fr]+1
                Parent[to]=fr
                que2.append(to)
        que.extend(que2)
        que2=deque()
        Visited[fr]=True
    return Euler,Depth,Parent

n,q=map(int,input().split())
Edgedict=[dict() for _ in range(n)]
for _ in range(n-1):
    a,b,c,d=map(int,input().split())
    a-=1; b-=1
    Edgedict[a][b]=(c,d)
    Edgedict[b][a]=(c,d)
Queries=[tuple(map(int,input().split())) for _ in range(q)]
Euler,Depth,Parent=Eulertour(Edgedict,n)
lca=LCA(n,Edgedict,Depth,Parent)
Q=[[] for _ in range(n)]
for i,(x,y,u,v) in enumerate(Queries):
    u-=1; v-=1
    Q[u].append([i,x,y,True])
    Q[v].append([i,x,y,True])
    Q[lca.lca(u,v)].append([i,x,y,False])
Ans=[0]*q
dist=0
C_len=[0]*n
C_cnt=[0]*n
for i in range(1,len(Euler)):
    idx=Euler[i][1]
    c,l=Edgedict[Euler[i-1][1]][idx]
    if Euler[i-1][0]<Euler[i][0]:
        dist+=l
        C_len[c]+=l
        C_cnt[c]+=1
        for q_idx,x,y,flag in Q[idx]:
            if flag:
                Ans[q_idx]+=dist+C_cnt[x]*y-C_len[x]
            else:
                Ans[q_idx]-=(dist+C_cnt[x]*y-C_len[x])*2
    else:
        dist-=l
        C_len[c]-=l
        C_cnt[c]-=1
print(*Ans,sep='\n')
```


p03127 AtCoder Beginner Contest 118 - Monsters Battle Royale

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

* A random alive monster attacks another random alive monster.
* As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

* All values in input are integers.
* 2 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Examples

Input

4
2 10 8 40

Output

2

Input

4
5 13 8 1000000000

Output

1

Input

3
1000000000 1000000000 1000000000

Output

1000000000

```python
from fractions import gcd
from functools import reduce
n, *A = map(int, open(0).read().split())
print(reduce(gcd, A))
```


p03270 AtCoder Regular Contest 102 - Stop. Otherwise...

Takahashi throws N dice, each having K sides with all integers from 1 to K. The dice are NOT pairwise distinguishable. For each i=2,3,...,2K, find the following value modulo 998244353:

* The number of combinations of N sides shown by the dice such that the sum of no two different sides is i.

Note that the dice are NOT distinguishable, that is, two combinations are considered different when there exists an integer k such that the number of dice showing k is different in those two.

Constraints

* 1 \leq K \leq 2000
* 2 \leq N \leq 2000
* K and N are integers.

Input

Input is given from Standard Input in the following format:

K N

Output

Print 2K-1 integers. The t-th of them (1\leq t\leq 2K-1) should be the answer for i=t+1.

Examples

Input

3 3

Output

7
7
4
7
7

Input

4 5

Output

36
36
20
20
20
36
36

Input

6 1000

Output

149393349
149393349
668669001
668669001
4000002
4000002
4000002
668669001
668669001
149393349
149393349

```python
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect

def read():
  return int(input())

def reads():
  return [int(x) for x in input().split()]

K, N = reads()
MOD = 998244353

MAXN = 4020

fact = [1] * MAXN
for i in range(1, MAXN): fact[i] = (fact[i-1] * i) % MOD
invfact = [0] * MAXN; invfact[-1] = pow(fact[-1], MOD-2, MOD)
for i in range(MAXN-2, -1, -1): invfact[i] = invfact[i+1] * (i+1) % MOD
def comb(n, k):
  return fact[n] * invfact[n-k] * invfact[k] % MOD if 0 <= k <= n else 0
def h(n, k):
  return comb(n+k-1, n)

def solve(n, k, u):
  ans = 0
  for q in range(u+1):
    ans = (ans + comb(u, q) * pow(2, u-q, MOD) % MOD * h(n-u+q, k-q-u)) % MOD
  return ans

anss = [0] * (2*K+1)
for i in range(2, K+2):
  u = sum(j < i-j <= K for j in range(1, K+1))
  if i % 2 == 1:
    ans = solve(N, K, u)
  else:
    ans = (solve(N, K-1, u) + solve(N-1, K-1, u)) % MOD
  anss[i] = ans
  print(ans)

for j in range(K+2, 2*K+1):
  print(anss[2*K - j + 2])

```


p03427 AtCoder Grand Contest 021 - Digit Sum 2

Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Constraints

* 1\leq N \leq 10^{16}
* N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.

Examples

Input

100

Output

18

Input

9995

Output

35

Input

3141592653589793

Output

137


p03585 Tenka1 Programmer Contest - CARtesian Coodinate

There are N lines in the xy-plane. The i-th line is represented by A_ix+B_iy=C_i. Any two lines among the N+2 lines, the above N lines plus the x-axis and y-axis, cross each other at exactly one point.

For each pair 1 \leq i < j \leq N, there is a car at the cross point of the i-th and j-th lines. Even where three or more lines intersect at a point, a car is individually placed for each pair of lines. That is, there will be k(k-1)/2 cars placed at the intersection of k lines.

Those cars are already very old, and can only be moved parallel to the x-axis or y-axis.

Takahashi will hold an exhibition of antique cars at a place on the xy-plane. In order to avoid damaging the half-broken cars too much, he will select the place of the exhibition so that the total distance covered will be minimized when all the cars are moved to the place. If such a place is not uniquely determined, among the places that satisfy the condition above, the place with the minimum x-coordinate will be selected. If the place is still not uniquely determined, among the places that satisfy the two conditions above, the place with the minimum y-coordinate will be selected.

Find the place of the exhibition that will be selected.

Constraints

* 2 \leq N \leq 4 × 10^4
* 1 \leq |A_i|,|B_i| \leq 10^4(1 \leq i \leq N)
* 0 \leq |C_i| \leq 10^4(1 \leq i \leq N)
* No two given lines are parallel.
* All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
A_1 B_1 C_1
:
A_N B_N C_N

Outputs

Print the x-coordinate and y-coordinate of the place of the exhibition that will be selected, in this order, with a space in between. The output will be judged as correct when the absolute or relative error is at most 10^{-9}.

Examples

Input

3
1 1 1
2 -1 2
-1 2 2

Output

1.000000000000000 1.000000000000000

Input

4
1 1 2
1 -1 0
3 -1 -2
1 -3 4

Output

-1.000000000000000 -1.000000000000000

Input

7
1 7 8
-2 4 9
3 -8 -5
9 2 -14
6 7 5
-8 -9 3
3 8 10

Output

-1.722222222222222 1.325000000000000

```python
def addbit(i):
    i += 1
    while i <= N:
        BIT[i] += 1
        i += i & (-i)
def getsum(i):
    ret = 0
    i += 1
    while i != 0:
        ret += BIT[i]
        i -= i&(-i)
    return ret
def bit(L):
    global BIT
    BIT=[0] * (N+1)
    re = 0
    for l in L:
        re += getsum(l)
        addbit(l)
    return N*(N-1)//2 - re
def get_rank(L):
    D = {x:i for i,x in enumerate(sorted(L))}
    return [D[x] for x in L]
def calc(Z):
    Z.sort()
    l, r = -1<<28, 1<<28
    while (r - l) / max(abs(l), 1) > 0.000000001:
        m = (l+r)/2
        A = get_rank([s*m+t for s, t in Z])
        c = bit(A)
        if c > N*(N-1)//4:
            l = m
        else:
            r = m
    return l

N = int(input())
X, Y = [], []
for _ in range(N):
    a, b, c = map(int, input().split())
    X.append((-a/b, c/b))
    Y.append((-b/a, c/a))
print(calc(X), calc(Y))
```


p03743 AtCoder Regular Contest 072 - Alice in linear land

Alice lives on a line. Today, she will travel to some place in a mysterious vehicle. Initially, the distance between Alice and her destination is D. When she input a number x to the vehicle, it will travel in the direction of the destination by a distance of x if this move would shorten the distance between the vehicle and the destination, and it will stay at its position otherwise. Note that the vehicle may go past the destination when the distance between the vehicle and the destination is less than x.

Alice made a list of N numbers. The i-th number in this list is d_i. She will insert these numbers to the vehicle one by one.

However, a mischievous witch appeared. She is thinking of rewriting one number in the list so that Alice will not reach the destination after N moves.

She has Q plans to do this, as follows:

* Rewrite only the q_i-th number in the list with some integer so that Alice will not reach the destination.

Write a program to determine whether each plan is feasible.

Constraints

* 1≤ N ≤ 5*10^5
* 1≤ Q ≤ 5*10^5
* 1≤ D ≤ 10^9
* 1≤ d_i ≤ 10^9(1≤i≤N)
* 1≤ q_i ≤ N(1≤i≤Q)
* D and each d_i are integers.

Input

Input is given from Standard Input in the following format:

N D
d_1 d_2 ... d_N
Q
q_1 q_2 ... q_Q

Output

Print Q lines. The i-th line should contain `YES` if the i-th plan is feasible, and `NO` otherwise.

Examples

Input

4 10
3 4 3 3
2
4 3

Output

NO
YES

Input

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

Output

YES
YES
YES
YES
YES

Input

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

Output

NO
NO
YES
NO
NO
YES

```python
N, D = map(int, input().split())
d = list(map(int, input().split()))
Q = int(input())
q = list(map(lambda x : int(x)-1 , input().split()))

dis = [0 for i in range(N+1)]
dis[0] = D
for i in range(N):
    dis[i+1] = min(dis[i], abs(dis[i] - d[i]))

dp = [0 for i in range(N+1)]
dp[N] = 1
for i in range(N-1, -1, -1):
    if d[i] // 2 >= dp[i+1]:
        dp[i] = dp[i+1]
    else:
        dp[i] = dp[i+1] + d[i]

for qi in range(Q):
    print(["YES", "NO"][dis[q[ qi ]] < dp[q[ qi ] + 1]])
```


p03903 CODE FESTIVAL 2016 Elimination Tournament Round 1 (Parallel) - Graph

Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i.

He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subset of the edges such that any vertex can be reached from at least one of the vertices S_i or T_i by traversing chosen edges.

For each round, find the minimum possible total weight of the edges chosen by Takahashi.

Constraints

* 1 ≦ N ≦ 4,000
* 1 ≦ M ≦ 400,000
* 1 ≦ Q ≦ 100,000
* 1 ≦ a_i,b_i,S_i,T_i ≦ N
* 1 ≦ c_i ≦ 10^{9}
* a_i \neq b_i
* S_i \neq T_i
* The given graph is connected.

Input

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

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M
Q
S_1 T_1
S_2 T_2
:
S_Q T_Q

Output

Print Q lines. The i-th line should contain the minimum possible total weight of the edges chosen by Takahashi.

Examples

Input

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

Output

8
7

Input

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

Output

8

```python
from collections import deque
import sys
sys.setrecursionlimit(10**5)

N, M = map(int, input().split())
E = []
for i in range(M):
    a, b, c = map(int, input().split())
    E.append((c, a-1, b-1))
E.sort()

*p, = range(N)
def root(x):
    if x == p[x]:
        return x
    p[x] = y = root(p[x])
    return y

L = 2*N-1
G = [[]] * L
C = [0]*L
*lb, = range(N)
cur = N

s = 0
for c, a, b in E:
    pa = root(a); pb = root(b)
    if pa == pb:
        continue
    s += c
    chds = [lb[pa], lb[pb]]
    if pa < pb:
        p[pb] = pa
        lb[pa] = cur
    else:
        p[pa] = pb
        lb[pb] = cur
    C[cur] = c
    G[cur] = chds
    cur += 1

H = [0]*L
prv = [-1]*L
def dfs(v):
    s = 1; heavy = -1; m = 0
    for w in G[v]:
        prv[w] = v
        c = dfs(w)
        if m < c:
            heavy = w
            m = c
        s += c
    H[v] = heavy
    return s
dfs(L-1)

SS = []
D = []
LB = [0]*L
I = [0]*L
que = deque([(L-1, 0)])
while que:
    v, d = que.popleft()
    S = []
    k = len(SS)
    while v != -1:
        I[v] = len(S)
        S.append(v)
        LB[v] = k
        h = H[v]
        for w in G[v]:
            if h == w:
                continue
            que.append((w, d+1))
        v = h
    SS.append(S)
    D.append(d)

def query(u, v):
    lu = LB[u]; lv = LB[v]
    dd = D[lv] - D[lu]
    if dd < 0:
        lu, lv = lv, lu
        v, u = u, v
        dd = -dd

    for _ in range(dd):
        v = prv[SS[lv][0]]
        lv = LB[v]

    while lu != lv:
        u = prv[SS[lu][0]]
        lu = LB[u]

        v = prv[SS[lv][0]]
        lv = LB[v]

    return u if I[u] < I[v] else v

def gen():
    Q = int(input())
    for i in range(Q):
        u, v = map(int, input().split())
        w = query(u-1, v-1)
        yield "%d\n" % (s - C[w])
ans = list(gen())
sys.stdout.writelines(ans)
```


p00009 Prime Number

Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Input

Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.

The number of datasets is less than or equal to 30.

Output

For each dataset, prints the number of prime numbers.

Example

Input

10
3
11

Output

4
2
5

```python
import sys
import math

LIMIT = 1000000
p = 2
pList = [True] * (LIMIT + 1)

while p ** 2 <= LIMIT:
    if(pList[p]):
        for i in range(p * 2, LIMIT + 1 , p):
            pList[i] = False
    p += 1

# print(pList)

lines = str(sys.stdin.read()).strip().split("\n")

for line in lines:
    line = int(line)
    count = 0
    for i in range(2, line + 1):
        if pList[i]:
            count += 1
    print(count)
```


p00141 Spiral Pattern

I decided to create a program that displays a "round and round pattern". The "round and round pattern" is as follows.

* If the length of one side is n, it is displayed as a character string with n rows and n columns.
* A spiral pattern that rotates clockwise with the lower left corner as the base point.
* The part with a line is represented by # (half-width sharp), and the blank part is represented by "" (half-width blank).
* Leave a space between the lines.

Create a program that takes an integer n as an input and outputs a "round and round pattern" with a side length of n.

Input

The input is given in the following format:

d
n1
n2
::
nd

The number of datasets d (d ≤ 20) is given to the first line, and the side length ni (1 ≤ ni ≤ 100) of the i-th round pattern is given to each of the following d lines.

Output

Please output a round and round pattern for each data set. Insert a blank line between the datasets.

Example

Input

2
5
6

Output

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

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

```python
vector = ((0, -1), (1, 0), (0, 1), (-1, 0))

def make_guruguru(d):
  lst = [["#"] * (d + 4)]
  for _ in range(d + 2):
    lst.append(["#"] + [" "] * (d + 2) + ["#"])
  lst.append(["#"] * (d + 4))
  x, y = 2, d + 1
  lst[y][x] = "#"
  direct = 0
  vx, vy = vector[0]
  cnt = 1
  while True:
    while lst[y + vy * 2][x + vx * 2] == " ":
      lst[y + vy][x + vx] = "#"
      y += vy
      x += vx
      cnt += 1
    if cnt <= 1:
      break
    direct = (direct + 1) % 4
    vx, vy = vector[direct]
    cnt = 0
  for y in range(2, d + 2):
    print("".join(lst[y][2:-2]))

n = int(input())
make_guruguru(int(input()))
for _ in range(n - 1):
  print()
  make_guruguru(int(input()))

```


p00274 A Pair of Prizes

Jou and Yae are a good couple. Jou is collecting prizes for capsule toy vending machines (Gachapon), and even when they go out together, when they find Gachapon, they seem to get so hot that they try it several times. Yae was just looking at Jou, who looked happy, but decided to give him a Gachapon prize for his upcoming birthday present. Yae wasn't very interested in Gachapon itself, but hopefully he would like a match with Jou.

For Gachapon that Yae wants to try, one prize will be given in one challenge. You can see how many types of prizes there are, including those that are out of stock, and how many of each prize remains. However, I don't know which prize will be given in one challenge. Therefore, regardless of the order in which the prizes are given, create a program that outputs the minimum number of challenges required for Yae to get two of the same prizes.

input

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

N
k1 k2 ... kN

Each dataset has two lines, and the first line is given the integer N (1 ≤ N ≤ 10000), which indicates how many types of prizes there are. The next line is given the integer ki (0 ≤ ki ≤ 10000), which indicates how many prizes are left.

The number of datasets does not exceed 100.

output

For each dataset, the minimum number of challenges required to get two identical prizes is output. However, if it is not possible, NA is output.

Example

Input

2
3 2
3
0 1 1
1
1000
0

Output

3
NA
2

```python
# AOJ 0279: A Pair of Prizes
# Python3 2018.6.25 bal4u

while True:
	n = int(input())
	if n == 0: break
	k = list(map(int, input().split()))
	one, many = 0, 0
	for i in k:
		if i == 1: one += 1
		elif i > 1: many += 1
	print(one+many+1 if many > 0 else "NA")

```


p00462 Pizza

problem

JOI Pizza sells pizza home delivery along the d-meter-long ring road that runs through the city center.

JOI Pizza has n stores S1, ..., Sn on the loop line. The head office is S1. The distance from S1 to Si when moving the loop line clockwise is set to di meters. D2 , ..., dn is an integer greater than or equal to 1 and less than or equal to d -1. D2, ..., dn are all different. Bake and deliver pizza at the shortest store.

The location of the delivery destination is represented by an integer k that is greater than or equal to 0 and less than or equal to d -1. This means that the distance from the head office S1 to the delivery destination in the clockwise direction is k meters. Pizza delivery is done along the loop line and no other road is allowed. However, the loop line may move clockwise or counterclockwise.

For example, if the location of the store and the location of the delivery destination are as shown in the figure below (this example corresponds to Example 1 of "I / O example").

<image>

The store closest to the delivery destination 1 is S2, so the delivery is from store S2. At this time, the distance traveled from the store is 1. Also, the store closest to delivery destination 2 is S1 (main store), so store S1 (main store). ) To deliver to home. At this time, the distance traveled from the store is 2.

Total length of the loop line d, Number of JOI pizza stores n, Number of orders m, N --1 integer representing a location other than the main store d2, ..., dn, Integer k1, .. representing the location of the delivery destination Given ., km, create a program to find the sum of all orders for each order by the distance traveled during delivery (ie, the distance from the nearest store to the delivery destination).

input

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

The first line is a positive integer d (2 ≤ d ≤ 1000000000 = 109) that represents the total length of the loop line, the second line is a positive integer n (2 ≤ n ≤ 100000) that represents the number of stores, and the third line is A positive integer m (1 ≤ m ≤ 10000) is written to represent the number of orders. The n --1 lines after the 4th line are integers d2, d3, ..., dn that represent the location of stores other than the main store. (1 ≤ di ≤ d -1) is written in this order, and the integers k1, k2, ..., km (0 ≤ ki ≤ d) representing the delivery destination location are in the m lines after the n + 3rd line. --1) are written in this order.

Of the scoring data, for 40% of the points, n ≤ 10000 is satisfied. For 40% of the points, the total distance traveled and the value of d are both 1000000 or less. In the scoring data, the total distance traveled is 1000000000 = 109 or less.

When d is 0, it indicates the end of input. The number of data sets does not exceed 10.

output

For each data set, one integer representing the total distance traveled during delivery is output on one line.

Examples

Input

8
3
2
3
1
4
6
20
4
4
12
8
16
7
7
11
8
0

Output

3
3

Input

None

Output

None


p00652 Cutting a Chocolate

Turtle Shi-ta and turtle Be-ko decided to divide a chocolate. The shape of the chocolate is rectangle. The corners of the chocolate are put on (0,0), (w,0), (w,h) and (0,h). The chocolate has lines for cutting. They cut the chocolate only along some of these lines.

The lines are expressed as follows. There are  m  points on the line connected between (0,0) and (0,h), and between (w,0) and (w,h). Each i-th point, ordered by y value (i = 0 then y =0), is connected as cutting line. These lines do not share any point where 0 < x < w . They can share points where x = 0 or x = w . However, (0, li ) = (0,lj ) and (w,ri ) = (w,rj ) implies  i  =  j  . The following figure shows the example of the chocolate.

<image>

There are  n  special almonds, so delicious but high in calories on the chocolate. Almonds are circle but their radius is too small. You can ignore radius of almonds. The position of almond is expressed as (x,y) coordinate.

Two turtles are so selfish. Both of them have requirement for cutting.

Shi-ta's requirement is that the piece for her is continuous. It is possible for her that she cannot get any chocolate. Assume that the minimum index of the piece is  i  and the maximum is  k . She must have all pieces between  i  and  k . For example, chocolate piece 1,2,3 is continuous but 1,3 or 0,2,4 is not continuous.

Be-ko requires that the area of her chocolate is at least  S . She is worry about her weight. So she wants the number of almond on her chocolate is as few as possible.

They doesn't want to make remainder of the chocolate because the chocolate is expensive.

Your task is to compute the minumum number of Beko's almonds if both of their requirment are satisfied.

Input

Input consists of multiple test cases.
Each dataset is given in the following format.

n m w h S
l0 r0
...
lm-1 rm-1
x0 y0
...
xn-1 yn-1

The last line contains five 0s. n is the number of almonds. m is the number of lines. w is the width of the chocolate. h is the height of the chocolate. S is the area that Be-ko wants to eat. Input is integer except xi yi.

Input satisfies following constraints.
1 ≤ n ≤ 30000
1 ≤ m ≤ 30000
1 ≤ w ≤ 200
1 ≤ h ≤ 1000000
0 ≤ S ≤ w*h

If i < j  then  li ≤ lj and  ri ≤ rj and then  i -th lines and  j -th lines share at most 1 point. It is assured that lm-1 and rm-1 are h. xi yi is floating point number with ten digits. It is assured that they are inside of the chocolate. It is assured that the distance between points and any lines is at least 0.00001.

Output

You should output the minumum number of almonds for Be-ko.

Example

Input

2 3 10 10 50
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 70
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 30
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 40
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 100
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
0 0 0 0 0

Output

1
1
0
1
2

```python
# AOJ 1067 Cutting a Chocolate
# Python3 2018.7.10 bal4u

from bisect import bisect_left

while True:
	n, m, w, h, S = map(int, input().split())
	if n == 0: break
	m, wh2 = m+1, 2*(w*h)
	S = wh2-2*S
	tbl, s = [[0,0,0,0]], [0]
	for i in range(1, m):
		l, r = map(int, input().split())
		tbl.append([l, r, 0, r-l])
		s.append((l+r)*w)
	p = []
	for i in range(n):
		x, y = map(float, input().split())
		p.append((x, y))
	p.sort(key=lambda x:(x[1],x[0]))
	j = 1
	for i in range(n):
		x, y = p[i]
		while True:
			y1 = tbl[j-1][3]*x/w + tbl[j-1][0]
			y2 = tbl[j  ][3]*x/w + tbl[j  ][0]
			if y1 < y:
				if y < y2: break
				j += 1
			else: j -= 1
		tbl[j][2] += 1
	for i in range(1, m): tbl[i][2] += tbl[i-1][2]
	if S == 0:
		print(n)
		continue
	elif S == wh2:
		print(0)
		continue
	j = bisect_left(s, S, 0, m)
	if s[j] != S: j -= 1
	ans, i = tbl[j][2], 1
	while j+1 < m:
		j += 1
		while s[j]-s[i] > S: i += 1
		ans = max(ans, tbl[j][2]-tbl[i][2])
	print(n - ans)

```


p00928 Automotive Navigation

Example

Input

4 2 1 1
1 1 1 2
2 2 2 1
2 2 1 2
1 1 2 1
9 N

Output

1 1
2 2

```python
# coding: utf-8
import sys
sys.setrecursionlimit(50000000)
max_c=101
vec=[(0,2),(2,0),(0,-2),(-2,0)]
try:
    while True:
        log=[-1 for i in range(10001)]
        n,x0,y0,t=map(int,input().split())
        field=[[0 for i in range(max_c)]for i in range(max_c)]
        for i in range(n):
            a,b,c,d=map(lambda x:int(x)*2,input().split())
            if b==d:
                field[b][min(a,c):max(a,c)+1]=[1 for i in range(max(a,c)+1-min(a,c))]
            else:
                for p in field[min(b,d):max(b,d)+1]:
                    p[a]=1
        a,b=-1,-1
        pt=0
        for i in range(t):
            a,b=input().split()
            a=int(a)+pt
            pt=a
            b='NESW'.find(b)
            log[a]=b
        end_t=pt
        end_v=b
        ans=[]
        memo=set({})
        def check(t,x,y,v):
            if t>end_t or (log[t]!=-1 and not((v+2)%4!=log[t])) or ((t,x,y,v) in memo):
                return
            memo.add((t,x,y,v))
            if t==end_t:
                ex,ey=vec[end_v]
                if v==end_v or 0<=y+ey//2<=100 and 0<=x+ex//2<=100 and field[y+ey//2][x+ex//2]==1 and (v+2)%4!=end_v:
                    ans.append((x,y))
                return
            if log[t]!=-1 and v==log[t] or log[t]==-1:
                i=0
                for mx,my in vec:
                    if i==(v+2)%4:
                        i+=1
                        continue
                    nx,ny=x+mx,y+my
                    if 0<=nx<=100 and 0<=ny<=100 and field[ny-my//2][nx-mx//2]==1:
                        check(t+1,nx,ny,i)
                    i+=1
            elif log[t]!=-1:
                i=0
                for mx,my in vec:
                    if i!=log[t]:
                        i+=1
                        continue
                    nx,ny=x+mx,y+my
                    if 0<=nx<=100 and 0<=ny<=100 and field[ny-my//2][nx-mx//2]==1:
                        check(t+1,nx,ny,i)
                    i+=1

        for i in range(4):
            check(0,x0*2,y0*2,i)

        for q in sorted(set(ans)):
            print(q[0]//2,q[1]//2)
except:
    pass

```


p01061 Community Integration

Problem

There are N villages. Each village is numbered from 1 to N. Due to the recent merger boom, several villages have been merged. Two or more merged villages will become one new city, and villages that are not merged with any village will remain villages.

You will be given multiple pieces of information that two villages will be in the same city after the merger. Depending on the combination of the information, three or more villages can become one city.

Given information about villages that will be in the same city after the merger, output the absolute value of the difference between the number of cities and the number of villages after the merger.

Constraints

* 1 ≤ N ≤ 1,000
* 0 ≤ M ≤ 100
* 1 ≤ ai ≤ N
* 1 ≤ bi ≤ N

Input

The input is given in the following format.

N M
a1 b1
a2 b2
...
ai bi
...
aM bM

The first line gives the number N of villages and the number M of information about the merger, separated by blanks.
From the second line to the M + 1 line, two integers ai and bi representing information about the merger are given, separated by blanks. Each information indicates that the ai and bi villages will be the same city after the merger. However, no input is given that satisfies ai = bi.

Output

Output the absolute value of the difference between the number of villages and the number of cities on one line.

Examples

Input

3 1
1 2

Output

0

Input

4 2
1 4
2 3

Output

2

Input

5 0

Output

5

Input

3 3
1 2
2 3
3 1

Output

1

Input

3 2
1 2
2 3

Output

1

Input

5 4
1 2
2 3
3 4
4 5

Output

1

Input

10 5
3 4
1 2
9 6
2 6
2 9

Output

2

```python
n, m = map(int, input().split())
q = []
for _ in range(m):
    a, b = map(int, input().split())
    i, j = -1, -1
    for k in range(len(q)):
        if i == -1:
            if a in q[k]:
                i = k
        if j == -1:
            if b in q[k]:
                j = k
        if i >= 0 and j >= 0:
            break
    if i >= 0:
        if j >= 0:
            if i != j:
                q[i] |= q[j]
                q.pop(j)
        else:
            q[i].add(b)
    elif j >= 0:
        q[j].add(a)
    else:
        q.append(set([a, b]))
print(abs(n - sum([len(i) for i in q]) - len(q)))

```


p01498 King Slime

There is a grid of size W × H surrounded by walls. Some cells in the grid are occupied by slimes. The slimes want to unite with each other and become a "King Slime".

In each move, a slime can move to east, west, south and north direction until it enters a cell occupied by another slime or hit the surrounding wall. If two slimes come together, they unite and become a new slime.

Your task is write a program which calculates the minimum number of moves that all the slimes unite and become a King Slime. Suppose slimes move one by one and they never move simultaneously.

Input

The first line contains three integers N (2 ≤ N ≤ 40,000), W and H (1 ≤ W, H ≤ 100,000), which denote the number of slimes, the width and the height of the grid respectively.

The following N lines describe the initial coordinates of the slimes. The i-th line contains two integers xi (1 ≤ xi ≤ W) and yi (1 ≤ yi ≤ H), which indicate the coordinates of the i-th slime . All the coordinates are 1-based.

You may assume that each cell is occupied by at most one slime initially.

Output

Output the minimum number of moves that all the slimes unite and become a King Slime.

Examples

Input

4 3 3
1 1
1 3
3 1
3 3

Output

3

Input

2 3 3
2 2
3 3

Output

2

Input

2 4 4
2 2
3 3

Output

3

Input

2 4 4
2 2
2 3

Output

1

```python
import sys

class UnionFind:
    def __init__(self,sz):
        self.__ranks = [1] * sz
        self.__parents = [ i for i in range(sz) ]
    def find_parent(self, x):
        if x == self.__parents[x]:
            return x
        else:
            self.__parents[x] = self.find_parent(self.__parents[x])
            return self.__parents[x]
    def same(self, x, y):
        return self.find_parent(x) == self.find_parent(y)
    def unite(self, x, y):
        px = self.find_parent(x)
        py = self.find_parent(y)
        if px == py:
            return
        if self.__ranks[px] > self.__ranks[py]:
            self.__parents[py] = px
        else:
            self.__parents[px] = py
            if self.__ranks[px] == self.__ranks[py]:
                self.__ranks[py] += 1

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

    uf = UnionFind(n)
    xd = {}
    yd = {}
    is_edges_slime = False
    for i in range(n):
        x,y = map(int, sys.stdin.readline().split())

        if x == 1 or x == w:
            is_edges_slime = True
        if y == 1 or y == h:
            is_edges_slime = True

        if x in xd:
            uf.unite(xd[x], i)
        else:
            xd[x] = i

        if y in yd:
            uf.unite(yd[y], i)
        else:
            yd[y] = i

    root = set()
    for i in range(n):
        root.add( uf.find_parent(i) )

    if len(root) == 1:
        print(n - 1)
    else:
        ans = n - len(root) # ????´?????????¨??????
        ans += len(root) - (1 if is_edges_slime else 0) # ???????????????
        ans += len(root) - 1 # ????????°???????????????
        print(ans)

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


p01811 ABC Gene

ABC Gene

There is a gene sequence represented by the string `ABC`. You can rewrite this gene sequence by performing the following operations several times.

* Choose one of the letters `A`,` B`, `C`. Let this be x. Replace all x in the gene sequence with `ABC` at the same time.

Given a string S consisting only of `A`,` B`, and `C`. Determine if the gene sequence can be matched to S.

Constraints

* 1 ≤ | S | ≤ 5,000
* S consists only of `A`,` B`, and `C`.

Input Format

Input is given from standard input in the following format.

S

Output Format

Output `Yes` if the gene sequence can be matched to S, and` No` if it cannot be matched.

Sample Input 1

ABC

Sample Output 1

Yes

The gene sequence is `ABC` from the beginning.

Sample Input 2

AABCC

Sample Output 2

Yes

If you select `B` and perform the operation, it becomes` ABC` → `AABCC`.

Sample Input 3

AABCABC

Sample Output 3

No

For example, even if you select `C` and perform an operation, it does not change from` AABCC` to `AABCABC`. Since all `C`s are replaced with` ABC` at the same time, the actual result is `AABCC` →` AABABCABC`.

Example

Input

ABC

Output

Yes

```python
# coding: utf-8
moto=input()
s=moto
gene='ABC'
f=True
log=[]
while len(s)>3 and f:
    f=False
    if s[:3]=='ABC':
        s=s.replace('ABC','A')
        log.append('A')
        f=True
    elif s[len(s)-3:]=='ABC':
        s=s.replace('ABC','C')
        log.append('C')
        f=True
    elif 'ABC' in s:
        s=s.replace('ABC','B')
        log.append('B')
        f=True
if s!=gene:
    print('No')
    exit()
l=len(log)
for i in range(l):
    s=s.replace(log[l-1-i],'ABC')
if s==moto:
    print('Yes')
else:
    print('No')

```


p01946 Slimming Plan

Chokudai loves eating so much. However, his doctor Akensho told him that he was overweight, so he finally decided to lose his weight.

Chokudai made a slimming plan of a $D$-day cycle. It is represented by $D$ integers $w_0, ..., w_{D-1}$. His weight is $S$ on the 0-th day of the plan and he aims to reduce it to $T$ ($S > T$). If his weight on the $i$-th day of the plan is $x$, it will be $x + w_{i\%D}$ on the $(i+1)$-th day. Note that $i\%D$ is the remainder obtained by dividing $i$ by $D$. If his weight successfully gets less than or equal to $T$, he will stop slimming immediately.

If his slimming plan takes too many days or even does not end forever, he should reconsider it.

Determine whether it ends or not, and report how many days it takes if it ends.

Input

The input consists of a single test case formatted as follows.

$S$ $T$ $D$
$w_0 ... w_{D-1}$

The first line consists of three integers $S$, $T$, $D$ ($1 \leq S, T, D \leq 100,000, S > T$). The second line consists of $D$ integers $w_0, ..., w_{D-1}$ ($-100,000 \leq w_i \leq 100,000$ for each $i$).

Output

If Chokudai's slimming plan ends on the $d$-th day, print $d$ in one line. If it never ends, print $-1$.

Examples

Input

65 60 3
-2 3 -4

Output

4

Input

65 60 3
-2 10 -3

Output

-1

Input

100000 1 1
-1

Output

99999

Input

60 59 1
-123

Output

1

```python
S, T, D = map(int, input().split())
S -= T
*W, = map(int, input().split())
F = sum(W)
if F >= 0:
    su = S
    for i, w in enumerate(W):
        su += w
        if su <= 0:
            print(i+1)
            break
    else:
        print(-1)
    exit(0)
su = 0
mi = 0
for d in W:
    su += d
    mi = min(mi, su)

k = max((S+mi-F-1) // -F, 0)
S += k*F
for i, w in enumerate(W):
    S += w
    if S <= 0:
        print(i+1+k*D)
        break
else:
    assert 0

```


p02233 Fibonacci Number

Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:

\begin{equation*} fib(n)= \left \\{ \begin{array}{ll} 1 & (n = 0) \\\ 1 & (n = 1) \\\ fib(n - 1) + fib(n - 2) & \\\ \end{array} \right. \end{equation*}

Constraints

* $0 \leq n \leq 44$

Input

An integer $n$ is given.

Example

Input

3

Output

3

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

num = [1,1]

for i in range(2,45):
  f = num[i - 1] + num[i - 2]
  num.append(f)

print(num[n])

```


p02379 Distance

Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

Four real numbers x1, y1, x2 and y2 are given in a line.

Output

Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Example

Input

0 0 1 1

Output

1.41421356


1019_B. The hat

This is an interactive problem.

Imur Ishakov decided to organize a club for people who love to play the famous game «The hat». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 ≤ i ≤ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.

As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.

You can ask questions of form «which number was received by student i?», and the goal is to determine whether the desired pair exists in no more than 60 questions.

Input

At the beginning the even integer n (2 ≤ n ≤ 100 000) is given — the total number of students.

You are allowed to ask no more than 60 questions.

Output

To ask the question about the student i (1 ≤ i ≤ n), you should print «? i». Then from standard output you can read the number ai received by student i ( - 109 ≤ ai ≤ 109).

When you find the desired pair, you should print «! i», where i is any student who belongs to the pair (1 ≤ i ≤ n). If you determined that such pair doesn't exist, you should output «! -1». In both cases you should immediately terminate the program.

The query that contains your answer is not counted towards the limit of 60 queries.

Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language.

Hacking

Use the following format for hacking:

In the first line, print one even integer n (2 ≤ n ≤ 100 000) — the total number of students.

In the second line print n integers ai ( - 109 ≤ ai ≤ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or  - 1.

The hacked solution will not have direct access to the sequence ai.

Examples

Input

8

2

2

Output

? 4

? 8

! 4

Input

6

1

2

3

2

1

0

Output

? 1

? 2

? 3

? 4

? 5

? 6

! -1

Note

Input-output in statements illustrates example interaction.

In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2

In the second sample the selection sequence is 1, 2, 3, 2, 1, 0.

```python

# this sequence is a bit scary
# 8
# 1 2 3 2 3 2 1 0

import sys
#sys.stdin=open("data.txt")
#input=sys.stdin.readline

got=[10**18]*100005

def getnum(i):
    if got[i]==10**18:
        print("? %d"%i)
        sys.stdout.flush()
        got[i]=int(input())
    return got[i]

n=int(input())
if n%4==2:
    # the opposite person has a different parity
    print("! -1")
else:
    lo=1
    hi=n//2+1
    t1=getnum(lo)
    t2=getnum(hi)
    lo2=t1-t2
    hi2=t2-t1
    if lo2==0:
        print("! 1")
    else:
        # binary search
        # let's hope that 1 <= mid <= n/2
        while lo<hi:
            mid=(lo+hi)//2
            #print(lo,hi,mid)
            mid2=getnum(mid)-getnum(mid+n//2)
            if mid2==0:
                print("! %d"%mid)
                break
            if (lo2>0) == (mid2>0):
                lo=mid+1
            else:
                hi=mid-1
        else:
            print("! %d"%lo)
sys.stdout.flush()

```


1042_A. Benches

There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.

Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k.

Nobody leaves the taken seat during the whole process.

Input

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of benches in the park.

The second line contains a single integer m (1 ≤ m ≤ 10 000) — the number of people additionally coming to the park.

Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ 100) — the initial number of people on the i-th bench.

Output

Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park.

Examples

Input

4
6
1
1
1
1

Output

3 7

Input

1
10
5

Output

15 15

Input

3
6
1
6
5

Output

6 12

Input

3
7
1
6
5

Output

7 13

Note

In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench.

The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it.

```python
import math
n=int(input())
m=int(input())
a=[]
for i in range(n):
	a.append(int(input()))
maxa=max(a)+m
mina=max(max(a),math.ceil((sum(a)+m)/n))
print(str(mina)+" "+str(maxa))

```


1106_D. Lunar New Year and a Wander

Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.

The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded.

Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.

A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds:

  * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length);
  * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y.

Input

The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively.

The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects.

Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.

Output

Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record.

Examples

Input

3 2
1 2
1 3

Output

1 2 3

Input

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

Output

1 4 3 2 5

Input

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

Output

1 4 3 7 9 8 6 5 2 10

Note

In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one.

In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.

```python
from heapq import heappush, heappop
n,m = map(int,input().split())

adj = [[] for _ in range(n)]

for _ in range(m):
    a,b = map(int,input().split())
    a-=1
    b-=1
    adj[a].append(b)
    adj[b].append(a)

st = set()
hp = []
v = [False for _ in range(n)]
heappush(hp,0)
v[0] = True
ans = []

while hp:
    x = heappop(hp)
    ans += [x]
    for i in adj[x]:
        if v[i]:
            continue
        v[i] = True
        heappush(hp,i)

print(*[i+1 for i in ans])
```


1133_E. K Balanced Teams

You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.

You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).

It is possible that some students not be included in any team at all.

Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.

Input

The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 5000) — the number of students and the maximum number of teams, correspondingly.

The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is a programming skill of the i-th student.

Output

Print one integer — the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.

Examples

Input

5 2
1 2 15 15 15

Output

5

Input

6 1
36 4 1 25 9 16

Output

2

Input

4 4
1 10 100 1000

Output

4

```python
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,k= kk()
ls = sorted(ll())
vs,ne = [0]*n,[-1]*n
b = 0
for a in range(n):
	while b < n and ls[b] - ls[a] < 6: b+=1
	vs[a],ne[a] = b-a, b
curr = [0]*(n+1)
# print(vs)
for _ in range(k):
	# print(curr)
	prev = curr
	curr = [0]*(n+1)
	for i in range(n):
		curr[i] = vs[i]+prev[ne[i]]
	m = 0
	for i in range(n-1, -1, -1):
		if m > curr[i]: curr[i]=m
		else: m = curr[i]
print(m)
```