1500_B. Two chandeliers

Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: red – brown – yellow – red – brown – yellow and so on.

There are many chandeliers that differs in color set or order of colors. And the person responsible for the light made a critical mistake — they bought two different chandeliers.

Since chandeliers are different, some days they will have the same color, but some days — different. Of course, it looks poor and only annoys Vasya. As a result, at the k-th time when chandeliers will light with different colors, Vasya will become very angry and, most probably, will fire the person who bought chandeliers.

Your task is to calculate the day, when it happens (counting from the day chandeliers were installed). You can think that Vasya works every day without weekends and days off.

Input

The first line contains three integers n, m and k (1 ≤ n, m ≤ 500 000; 1 ≤ k ≤ 10^{12}) — the number of colors in the first and the second chandeliers and how many times colors should differ to anger Vasya.

The second line contains n different integers a_i (1 ≤ a_i ≤ 2 ⋅ max(n, m)) that describe the first chandelier's sequence of colors.

The third line contains m different integers b_j (1 ≤ b_i ≤ 2 ⋅ max(n, m)) that describe the second chandelier's sequence of colors.

At the i-th day, the first chandelier has a color a_x, where x = ((i - 1) mod n) + 1) and the second one has a color b_y, where y = ((i - 1) mod m) + 1).

It's guaranteed that sequence a differs from sequence b, so there are will be days when colors of chandeliers differs.

Output

Print the single integer — the index of day when Vasya will become angry.

Examples

Input

4 2 4
4 2 3 1
2 1

Output

5

Input

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

Output

47

Input

1 2 31
1
1 2

Output

62

Note

In the first example, the chandeliers will have different colors at days 1, 2, 3 and 5. That's why the answer is 5.

```python
def main():
    n, m, k = list(map(lambda x: int(x), str(input()).split(' ')))
    a = list(map(lambda x: int(x), str(input()).split(' ')))
    b = list(map(lambda x: int(x), str(input()).split(' ')))
    if n < m:
        print(solve(m, n, k, b, a))
        return
    print(solve(n, m, k, a, b))

def solve(n, m, k, a, b):
    # n >= m
    d = gcd(n, m)

    x, y = 0, 0
    # x * n - y * m = d
    for i in range(1, m):
        if (i * n - d) % m == 0:
            x = i
            y = (i * n - d) // m
            if y == 0:
                x += 1
                y += 1
            break
    # print(x, y, d)
    common = {}
    common_count = 0
    colors = {}
    for i in range(len(a)):
        colors[a[i]] = i

    for i in range(len(b)):
        if b[i] in colors and (colors[b[i]] - i) % d == 0:
            common[colors[b[i]]] = i
            common_count += 1

    # where the common indices meet
    com = []

    for key, val in common.items():
        z = (val - key) // d
        # z * x * n - z * y * m = v - k
        com.append(int(((z * x) % (m // d)) * n + key))

    new_k = k % (m * n // d - common_count)
    s = (k // (m * n // d - common_count)) * m * n // d
    if new_k == 0:
        new_k = m * n // d - common_count
        s -= m * n // d

    com = sorted(com)
    cur = -1

    # print(com, s, new_k, common_count, m * n // d - common_count)
    for c in com:
        if new_k < c - cur:
            s += new_k
            return s
        new_k -= (c - cur - 1)
        s += (c - cur)
        cur = c
    return s + new_k

def gcd(n, m):
    if n == m:
        return n
    if n < m:
        return gcd(m, n)
    if n % m == 0:
        return m
    return gcd(m, n % m)

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


1525_D. Armchairs

There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2.

For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th armchair is occupied by someone and the j-th armchair is not, you can tell the person sitting in the i-th armchair to move to the j-th armchair. The time it takes a person to move from the i-th armchair to the j-th one is |i - j| minutes. You may perform this operation any number of times, but these operations must be done sequentially, i. e. you cannot tell a person to move until the person you asked to move in the last operation has finished moving to their destination armchair.

You want to achieve the following situation: every seat that was initially occupied must be free. What is the minimum time you need to do it?

Input

The first line contains one integer n (2 ≤ n ≤ 5000) — the number of armchairs.

The second line contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 1). a_i = 1 means that the i-th armchair is initially occupied, a_i = 0 means that it is initially free. The number of occupied armchairs is at most n/2.

Output

Print one integer — the minimum number of minutes you have to spend to achieve the following situation: every seat that was initially occupied must be free.

Examples

Input

7
1 0 0 1 0 0 1

Output

3

Input

6
1 1 1 0 0 0

Output

9

Input

5
0 0 0 0 0

Output

0

Note

In the first test, you can perform the following sequence:

  1. ask a person to move from armchair 1 to armchair 2, it takes 1 minute;
  2. ask a person to move from armchair 7 to armchair 6, it takes 1 minute;
  3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute.

In the second test, you can perform the following sequence:

  1. ask a person to move from armchair 1 to armchair 4, it takes 3 minutes;
  2. ask a person to move from armchair 2 to armchair 6, it takes 4 minutes;
  3. ask a person to move from armchair 4 to armchair 5, it takes 1 minute;
  4. ask a person to move from armchair 3 to armchair 4, it takes 1 minute.

In the third test, no seat is occupied so your goal is achieved instantly.

```python
import sys
input = sys.stdin.buffer.readline
import math

n=int(input())
arr=[int(x) for x in input().split()]

h=[]
v=[]
for i in range(n):
    if arr[i]:
        v.append(i)
    else:
        h.append(i)

hh=len(h)
vv=len(v)
dp=[[0 for j in range(hh+1)] for i in range(vv+1)]

for i in range(1,vv+1):
    dp[i][0]=math.inf

for i in range(1,vv+1):
    for j in range(1,hh+1):
        dp[i][j]=min(dp[i-1][j-1]+abs(v[i-1]-h[j-1]),dp[i][j-1])

print(dp[vv][hh])
```


157_A. Game Outcome

Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.

<image>

For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 > 19.

Input

The first line contains an integer n (1 ≤ n ≤ 30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.

Output

Print the single number — the number of the winning squares.

Examples

Input

1
1

Output

0

Input

2
1 2
3 4

Output

2

Input

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

Output

6

Note

In the first example two upper squares are winning.

In the third example three left squares in the both middle rows are winning:

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

```python
n = int(input())
r = lambda : list(map(int, input().split()))
arr = []
for i in range(n):
    a = r()
    arr.append(a)

row = [sum(i) for i in arr]

col = []
for i in range(n):
    c = 0
    for j in range(n): c+=arr[j][i]
    col.append(c)

ans = 0
for i in range(n):
    for j in range(n):
        if row[i] < col[j]: ans+=1

print(ans)

```


178_A1. Educational Game

The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.

The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.

One move is choosing an integer i (1 ≤ i ≤ n) such that ai > 0 and an integer t (t ≥ 0) such that i + 2t ≤ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).

You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≤ k < n).

Input

The first input line contains a single integer n. The second line contains n integers ai (0 ≤ ai ≤ 104), separated by single spaces.

The input limitations for getting 20 points are:

  * 1 ≤ n ≤ 300

The input limitations for getting 50 points are:

  * 1 ≤ n ≤ 2000

The input limitations for getting 100 points are:

  * 1 ≤ n ≤ 105

Output

Print exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero.

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

Examples

Input

4
1 0 1 2

Output

1
1
3

Input

8
1 2 3 4 5 6 7 8

Output

1
3
6
10
16
24
40

```python
n = int(input())
a = [int(t) for t in input().split()]

c = 0
for i in range(n - 1):
    if a[i] > 0:
        c += a[i]
        print(c)
        j = 0
        while 2 ** j + i < n:
            j += 1

        a[2 ** (j - 1) + i] += a[i]
        a[i] = 0
    else:
        print(c)
```


19_B. Checkout Assistant

Bob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.

Input

The first input line contains number n (1 ≤ n ≤ 2000). In each of the following n lines each item is described by a pair of numbers ti, ci (0 ≤ ti ≤ 2000, 1 ≤ ci ≤ 109). If ti is 0, Bob won't be able to steal anything, while the checkout assistant is occupied with item i.

Output

Output one number — answer to the problem: what is the minimum amount of money that Bob will have to pay.

Examples

Input

4
2 10
0 20
1 5
1 3

Output

8

Input

3
0 1
0 10
0 100

Output

111

```python
n=int(input())
ar=[float('inf')]*(n+1)
ar[0]=0
for i in range(n):
    t,c=map(int,input().split())
    for j in range(n-1,-1,-1):
        w=min(j+t+1,n)
        ar[w]=min(ar[w],ar[j]+c)
print(ar[n])

```


223_C. Partial Sums

You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:

  1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals <image>. The operation x mod y means that we take the remainder of the division of number x by number y.
  2. Then we write the contents of the array s to the array a. Element number i (1 ≤ i ≤ n) of the array s becomes the i-th element of the array a (ai = si).

You task is to find array a after exactly k described operations are applied.

Input

The first line contains two space-separated integers n and k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 109). The next line contains n space-separated integers a1, a2, ..., an — elements of the array a (0 ≤ ai ≤ 109).

Output

Print n integers — elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces.

Examples

Input

3 1
1 2 3

Output

1 3 6

Input

5 0
3 14 15 92 6

Output

3 14 15 92 6

```python
n, k = map(int, input().split())
num = list(map(int, input().split()))
MOD = 10 ** 9 + 7

cf = [1]
for i in range(1, 2020):
    cf.append((cf[-1] * (k + i - 1) * pow(i, MOD - 2, MOD)) % MOD)

ans = [0 for i in range(n)]
for i in range(n):
    for j in range(i + 1):
        ans[i] = (ans[i] + cf[i - j] * num[j]) % MOD

print(' '.join(map(str, ans)))

# Made By Mostafa_Khaled
```


248_A. Cupboards

One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.

Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.

And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.

Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.

Your task is to write a program that will determine the required number of seconds t.

Input

The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero.

The numbers in the lines are separated by single spaces.

Output

In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.

Examples

Input

5
0 1
1 0
0 1
1 1
0 1

Output

3

```python
k = int(input())
lo=ro=rc=lc=0
for _ in range(k):
    n , m = map(int,input().split())
    if(n==0):
        lo+=1
    else:
         lc=lc+1
    if(m==0):
         ro+=1
    else :
         rc=rc+1
print(min(lo,lc)+min(ro,rc))

```


272_B. Dima and Sequence

Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence:

  * f(0) = 0;
  * f(2·x) = f(x);
  * f(2·x + 1) = f(x) + 1.

Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤ n) are there, such that f(ai) = f(aj). Help him, count the number of such pairs.

Input

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).

The numbers in the lines are separated by single spaces.

Output

In a single line print the answer to the problem.

Please, don't use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

Examples

Input

3
1 2 4

Output

3

Input

3
5 3 1

Output

1

Note

In the first sample any pair (i, j) will do, so the answer is 3.

In the second sample only pair (1, 2) will do.

```python
def f(x):
	return str(bin(x)).count('1')
n = int(input())
a = list(map(int, input().split()))
ans = [f(x) for x in a]
s = set(ans)
counts = {x:ans.count(x) for x in s}
ans = 0
for i in counts:
	ans += (counts[i]*(counts[i]-1))//2
print(ans)
```


319_B. Psychos in a Line

There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step.

You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.

Input

The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right.

Output

Print the number of steps, so that the line remains the same afterward.

Examples

Input

10
10 9 7 8 6 5 3 4 2 1

Output

2

Input

6
1 2 3 4 5 6

Output

0

Note

In the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1]  →  [10 8 4] →  [10]. So, there are two steps.

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

p, s, r = [0] * n, [0] * n, t[0]

for i in range(n - 1):

    j = i + 1

    x = t[j]

    if x > r: r = x

    else:

        while t[i] < x: s[j], i = max(s[j], s[i]), p[i]

        p[j] = i

        s[j] += 1

print(max(s))

# Made By Mostafa_Khaled
```


343_B. Alternating Current

Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.

The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):

<image>

Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.

To understand the problem better please read the notes to the test samples.

Input

The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.

Output

Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.

Examples

Input

-++-

Output

Yes

Input

+-

Output

No

Input

++

Output

Yes

Input

-

Output

No

Note

The first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.

In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled:

<image>

In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher:

<image>

In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:

<image>

```python
list_inp=input()
stack_jud=[]
for i in list_inp:
    if len(stack_jud)>0:
        if stack_jud[-1]==i:stack_jud.pop()
        else: stack_jud.append(i)
    else: stack_jud.append(i)
if stack_jud==[]:print ('Yes')
else:print ('No')

```


38_C. Blinds

The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)

Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)

After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.

Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k × d bourlemeters.

Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.

Input

The first output line contains two space-separated integers n and l (1 ≤ n, l ≤ 100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1 ≤ ai ≤ 100).

Output

Print the single number — the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.

Examples

Input

4 2
1 2 3 4

Output

8

Input

5 3
5 5 7 3 1

Output

15

Input

2 3
1 2

Output

0

Note

In the first sample test the required window is 2 × 4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves.

```python
m, l = map(int, input().split())
a = list(map(int, input().split()))
print(max(i * sum(ai // i for ai in a) for i in range(l, 101)))
```


40_B. Repaintings

A chessboard n × m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues ad infinitum. You have to figure out how many squares we repainted exactly x times.

The upper left square of the board has to be assumed to be always black. Two squares are called corner-adjacent, if they have exactly one common point.

Input

The first line contains integers n and m (1 ≤ n, m ≤ 5000). The second line contains integer x (1 ≤ x ≤ 109).

Output

Print how many squares will be painted exactly x times.

Examples

Input

3 3
1

Output

4

Input

3 3
2

Output

1

Input

1 1
1

Output

1

```python
import itertools
import math

n, m = [int(k) for k in input().split()]
x = int(input())
if n-2*(x-1) < 1 or m-2*(x-1) < 1:
    print(0)
elif n-2*(x-1) == 1 or m-2*(x-1) == 1:
    print((n+m-4*(x-1))//2)
else: print(n+m-2 - 4*(x-1))

```


438_A. The Child and Toy

On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.

The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.

Help the child to find out, what is the minimum total energy he should spend to remove all n parts.

Input

The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi).

Consider all the parts are numbered from 1 to n.

Output

Output the minimum total energy the child should spend to remove all n parts of the toy.

Examples

Input

4 3
10 20 30 40
1 4
1 2
2 3

Output

40

Input

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

Output

400

Input

7 10
40 10 20 10 20 80 40
1 5
4 7
4 5
5 2
5 7
6 4
1 6
1 3
4 3
1 4

Output

160

Note

One of the optimal sequence of actions in the first sample is:

  * First, remove part 3, cost of the action is 20.
  * Then, remove part 2, cost of the action is 10.
  * Next, remove part 4, cost of the action is 10.
  * At last, remove part 1, cost of the action is 0.

So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.

In the second sample, the child will spend 400 no matter in what order he will remove the parts.

```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))

def main():
    n,m = LI()
    a = LI()
    aa = [LI_() for _ in range(m)]
    r = 0
    for b,c in aa:
        r += min(a[b], a[c])

    return r

print(main())

```


45_H. Road Problem

The Berland capital (as you very well know) contains n junctions, some pairs of which are connected by two-way roads. Unfortunately, the number of traffic jams in the capital has increased dramatically, that's why it was decided to build several new roads. Every road should connect two junctions.

The city administration noticed that in the cities of all the developed countries between any two roads one can drive along at least two paths so that the paths don't share any roads (but they may share the same junction). The administration decided to add the minimal number of roads so that this rules was fulfilled in the Berland capital as well. In the city road network should exist no more than one road between every pair of junctions before or after the reform.

Input

The first input line contains a pair of integers n, m (2 ≤ n ≤ 900, 1 ≤ m ≤ 100000), where n is the number of junctions and m is the number of roads. Each of the following m lines contains a description of a road that is given by the numbers of the connected junctions ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). The junctions are numbered from 1 to n. It is possible to reach any junction of the city from any other one moving along roads.

Output

On the first line print t — the number of added roads. Then on t lines print the descriptions of the added roads in the format of the input data. You can use any order of printing the roads themselves as well as the junctions linked by every road. If there are several solutions to that problem, print any of them.

If the capital doesn't need the reform, print the single number 0.

If there's no solution, print the single number -1.

Examples

Input

4 3
1 2
2 3
3 4

Output

1
1 4

Input

4 4
1 2
2 3
2 4
3 4

Output

1
1 3

```python
import sys
import threading

def main():

    p = input().split()
    n = int(p[0]) #number of locations
    m = int(p[1]) #number of passages

    if n==1: #if there's only one location, there's nothing to do
        print(0)
        return
    if n==2: #if there's only two nodes, the only edge between them, is always a bridge
        print(-1)
        return

    g = graph(n,m)

    g.buildBridgeTree()

    e = graph(len(g.bridges)+1,len(g.bridges))

    e.conexions= []
    e.pi=[]
    e.discovery=[]
    e.seen=[]

    for i in range(len(g.bridges)+1):
        e.conexions.append([])
        e.pi.append(-1)
        e.discovery.append(sys.float_info.max)
        e.seen.append(False)
    for i in range(len(g.bridges)):
        e.conexions[g.cc[g.bridges[i][0]]].append((g.cc[g.bridges[i][1]],True))
        e.conexions[g.cc[g.bridges[i][1]]].append((g.cc[g.bridges[i][0]],True))

    e.bridges=g.bridges
    e.bridge=g.bridge
    e.cc=g.cc
    e.CC=e.CC
    e.CC

    e.treeDiameter()

    print(len(e.newEdges))
    for i in range(len(e.newEdges)):
        u = e.newEdges[i][0] +1
        v = e.newEdges[i][1] +1
        print(u, end=" ")
        print(v)

class graph:

    n = int() #number of nodes
    edges= int() #number of edges
    time = int()

    conexions = [] #adjacency list
    bridges=[] #are we using a removable edge or not for city i?
    bridge=[]

    discovery = [] #time to discover node i
    seen = [] #visited or not
    cc = [] #index of connected components
    low = [] #low[i]=min(discovery(i),discovery(w)) w:any node discoverable from i
    pi = [] #index of i's father

    CC = []
    newEdges = []

    def __init__(self, n, m):

        self.n = n
        self.edges = m

        for i in range(self.n):
            self.conexions.append([])
            self.discovery.append(sys.float_info.max)
            self.low.append(sys.float_info.max)
            self.seen.append(False)
            self.cc.append(-1)
            self.CC.append([])
            self.bridge.append([])

    def buildGraph(self):
        #this method put every edge in the adjacency list
        for i in range(self.edges):
            p2=input().split()
            self.conexions[int(p2[0])-1].append((int(p2[1])-1,False))
            self.conexions[int(p2[1])-1].append((int(p2[0])-1,False))

    def searchBridges (self):
        self.time = 0

        for i in range(self.n):
            self.pi.append(-1)
            for j in range(self.n):
                self.bridge[i].append(False)

        self.searchBridges_(0,-1) #we can start in any node 'cause the graph is connected

    def searchBridges_(self,c,index):

        self.seen[c]=True #mark as visited
        self.time+=1
        self.discovery[c]=self.low[c]= self.time

        for i in range(len(self.conexions[c])):

            pos = self.conexions[c][i][0]
            if not self.seen[pos]:
                self.pi[pos]=c #the node that discovered it

                self.searchBridges_(pos,i) #search throw its not visited conexions

                self.low[c]= min([self.low[c],self.low[pos]]) #definition of low

            elif self.pi[c]!=pos: #It is not the node that discovered it
                self.low[c]= min([self.low[c],self.discovery[pos]])

        if self.pi[c]!=-1 and self.low[c]==self.discovery[c]:  #it isn't the root and none of its connections is reacheable earlier than it
            self.bridges.append((c,self.pi[c]))
            self.bridge[self.pi[c]][c]=self.bridge[c][self.pi[c]]= True

            for i in range(len(self.conexions[c])):
                if(self.conexions[c][i][0]==self.pi[c]):
                    self.conexions[c][i]=(self.pi[c],True)
                    self.conexions[self.pi[c]][index]=(c,True)

    def findCC(self):

        j = 0

        for i in range(self.n):
            self.pi[i]=-1
            self.seen[i]=False

        for i in range(self.n):
            if self.seen[i]==False:
                self.cc[i]=j #assign the index of the new connected component
                self.CC[j].append(i)
                self.findCC_(i,j) #search throw its not visited conexions
                j+=1 #we finished the search in the connected component

    def findCC_(self, c, j):

        self.seen[c]=True #mark as visited

        for i in range(len(self.conexions[c])):

            pos = self.conexions[c][i][0]
            if(self.seen[pos]==False and self.conexions[c][i][1]==False):

                self.cc[pos]=j #assign the index of the connected component
                self.CC[j].append(pos)
                self.pi[pos]=c #the node that discovered it
                self.findCC_(pos,j) #search throw its not visited conexions

    def treeDiameter(self):

       while self.n>1:

            for i in range(self.n):
                self.seen[i]=False
                self.pi[i]=-1
            self.discovery[0]=0
            self.treeDiameter_(0) #search the distance from this node, to the others
            max = -1
            maxIndex = 0
            for i in range(self.n):
                if self.discovery[i]>max:
                    max= self.discovery[i] #look for the furthest node
                    maxIndex=i
            for i in range(self.n):
                self.seen[i]=False
                self.pi[i]=-1
            self.discovery[maxIndex]=0
            self.treeDiameter_(maxIndex)  #search the distance from the furthest node, to the others
            max =-1
            maxIndex2=-1
            for i in range(self.n):
                if self.discovery[i]>max :
                    max= self.discovery[i] #look for the furthest node to preview furthest node, and that is the diameter in a tree
                    maxIndex2=i

            self.ReBuildTree(maxIndex,maxIndex2)

    def treeDiameter_(self, c):

        self.seen[c]=True #mark as visited

        for i in range(len(self.conexions[c])):

            pos = self.conexions[c][i][0]

            if self.seen[pos]==False:

                self.pi[pos]=c #the node that discovered it
                self.discovery[pos]= self.discovery[c]+1 #distance to the node who discover it + 1
                #we don't have to compare and search for other paths, since it's a tree and there is only one path between two nodes.
                self.treeDiameter_(pos) #search throw its not visited conex16 ions

    def buildBridgeTree(self):

        self.buildGraph()
        self.searchBridges()
        self.findCC()

    def ReBuildTree(self, u, v):
        find=0

        for i in range(len(self.CC[u])):
            for j in range(len(self.CC[v])):
                if not self.bridge[self.CC[u][i]][self.CC[v][j]]:
                    self.newEdges.append((self.CC[u][i],self.CC[v][j]))
                    find=1
                    break

            if find==1:
                break

        newIndex=[]
        temp = v
        self.conexions[u]=None
        self.conexions[v]=None

        while self.pi[temp]!=u:
            self.conexions[self.pi[temp]]=None
            temp = self.pi[temp]

        r =1
        for i in range(self.n):
            if(self.conexions[i]!=None):
                newIndex.append(r)
                r+=1
            else:
                newIndex.append(0)

        self.n=r

        if self.n==1:
            return

        newCC=[]

        self.conexions=[]

        for i in range(self.n):
            self.conexions.append([])
            newCC.append([])

        for i in range(len(self.bridges)):

            len0 = len(self.CC[self.cc[self.bridges[i][0]]])

            if(len0!=0):
                for j in range(len0):
                    newCC[newIndex[self.cc[self.bridges[i][0]]]].append(self.CC[self.cc[self.bridges[i][0]]][j])
                self.CC[self.cc[self.bridges[i][0]]]=[]

            len1 = len(self.CC[self.cc[self.bridges[i][1]]])

            if(len1!=0):
                for j in range(len1):
                    newCC[newIndex[self.cc[self.bridges[i][1]]]].append(self.CC[self.cc[self.bridges[i][1]]][j])
                self.CC[self.cc[self.bridges[i][1]]]=[]

            self.conexions[newIndex[self.cc[self.bridges[i][0]]]].append((newIndex[self.cc[self.bridges[i][1]]],True))
            self.conexions[newIndex[self.cc[self.bridges[i][1]]]].append((newIndex[self.cc[self.bridges[i][0]]],True))

        self.CC= newCC

        for i in range(len(self.cc)):
            self.cc[i]=newIndex[self.cc[i]]

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


483_B. Friends and Presents

You have two friends. You want to present each of them several positive integers. You want to present cnt1 numbers to the first friend and cnt2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.

In addition, the first friend does not like the numbers that are divisible without remainder by prime number x. The second one does not like the numbers that are divisible without remainder by prime number y. Of course, you're not going to present your friends numbers they don't like.

Your task is to find such minimum number v, that you can form presents using numbers from a set 1, 2, ..., v. Of course you may choose not to present some numbers at all.

A positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.

Input

The only line contains four positive integers cnt1, cnt2, x, y (1 ≤ cnt1, cnt2 < 109; cnt1 + cnt2 ≤ 109; 2 ≤ x < y ≤ 3·104) — the numbers that are described in the statement. It is guaranteed that numbers x, y are prime.

Output

Print a single integer — the answer to the problem.

Examples

Input

3 1 2 3

Output

5

Input

1 3 2 3

Output

4

Note

In the first sample you give the set of numbers {1, 3, 5} to the first friend and the set of numbers {2} to the second friend. Note that if you give set {1, 3, 5} to the first friend, then we cannot give any of the numbers 1, 3, 5 to the second friend.

In the second sample you give the set of numbers {3} to the first friend, and the set of numbers {1, 2, 4} to the second friend. Thus, the answer to the problem is 4.

```python
c1,c2,x,y=map(int,input().split())
def fn(val):
    f=[val//x,val//y]
    both=val//(x*y)
    f=[i-both for i in f]
    oth=val-f[0]-f[1]-both
    cnt=[c1-f[1],c2-f[0]]
    if cnt[0]<0:cnt[0]=0
    if cnt[1] < 0: cnt[1] = 0
    return (sum(cnt)<=oth)
l=0;r=int(1e18)
while r-l>1:
    m=(r+l)//2
    if fn(m):
        r=m
    else:l=m
print(r)
```


507_B. Amr and Pins

Amr loves Geometry. One day he came up with a very interesting problem.

Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').

In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.

Help Amr to achieve his goal in minimum number of steps.

Input

Input consists of 5 space-separated integers r, x, y, x' y' (1 ≤ r ≤ 105,  - 105 ≤ x, y, x', y' ≤ 105), circle radius, coordinates of original center of the circle and coordinates of destination center of the circle respectively.

Output

Output a single integer — minimum number of steps required to move the center of the circle to the destination point.

Examples

Input

2 0 0 0 4

Output

1

Input

1 1 1 4 4

Output

3

Input

4 5 6 5 6

Output

0

Note

In the first sample test the optimal way is to put a pin at point (0, 2) and rotate the circle by 180 degrees counter-clockwise (or clockwise, no matter).

<image>

```python
import math #.sqrt
def ceil (a, b):
    return -(-a // b)
def answer(r, x, y, xp, yp):
    d = math.sqrt((xp-x)**2 + (yp-y)**2)
    num_rs = ceil(d, 2*r)

    return int(num_rs)

def main():
    r, x, y, xp, yp = [int(i) for i in input().split()]
    print(answer(r, x, y, xp, yp))

    return
main()
```


556_C. Case of Matryoshkas

Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.

The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1 → 2 → 4 → 5.

In one second, you can perform one of the two following operations:

  * Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b;
  * Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b.

According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1 → 2 → ... → n). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.

Input

The first line contains integers n (1 ≤ n ≤ 105) and k (1 ≤ k ≤ 105) — the number of matryoshkas and matryoshka chains in the initial configuration.

The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1 ≤ mi ≤ n), and then mi numbers ai1, ai2, ..., aimi — the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka).

It is guaranteed that m1 + m2 + ... + mk = n, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.

Output

In the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.

Examples

Input

3 2
2 1 2
1 3

Output

1

Input

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

Output

10

Note

In the first sample test there are two chains: 1 → 2 and 3. In one second you can nest the first chain into the second one and get 1 → 2 → 3.

In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds.

```python
n, m = [int(x) for x in input().split()]
a = []
for i in range(m):
    a.append([int(x) for x in input().split()][1:])
b = []
curt = 0
for i in a:
    j = 0
    b.append([])
    while (j < len(i)) and (i[j] == (j + 1)):
        j += 1
    if j != 0:
        b[-1] = [j]
    b[-1] += [1] * (len(i) - j)
    curt += len(b[-1])
fin = curt - 1
#print(b)
for i in b:
    fin += len(i) - 1
print(fin)

```


582_A. GCD Table

The GCD table G of size n × n for an array of positive integers a of length n is defined by formula

<image>

Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows:

<image>

Given all the numbers of the GCD table G, restore array a.

Input

The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a.

All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.

Output

In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.

Examples

Input

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

Output

4 3 6 2

Input

1
42

Output

42

Input

2
1 1 1 1

Output

1 1

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

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
# from collections import Counter
# from fractions import Fraction
# s=iter(input())
# for _ in range(int(input())):
# from collections import deque
# n=int(input())
# arr=list(map(int,input().split()))
# ls=list(map(int,input().split()))
# for i in range(m):
# for i in range(int(input())):
# arr = list(map(int, input().split()))
# for  i in range(int(input())):
# for  _ in range(int(input())):
# n, k = map(int, input().split())
def gcd(a,b):
    if b==0:
        return a
    return gcd(b,a%b)

n = int(input())
arr = sorted(list(map(int, input().split())))[::-1]
if arr==[1]*n**2:
    print("1 "*(n))
else:
    d={}
    ans=[]
    for i in range(n*n):
        if arr[i] in d:
            d[arr[i]]+=1
        else:
            d[arr[i]]=1
    for i in arr:
        if d[i]>0:
            ans.append(i)
            for j in ans:
                d[gcd(i,j)]-=2
    #ans=" ".join(ans)
    print(*ans)
```


604_A. Uncowed Forces

Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd as the best cowmputer scientist in all of Bovinia. Kevin knows his submission time for each problem, the number of wrong submissions that he made on each problem, and his total numbers of successful and unsuccessful hacks. Because Codeforces scoring is complicated, Kevin wants you to write a program to compute his final score.

Codeforces scores are computed as follows: If the maximum point value of a problem is x, and Kevin submitted correctly at minute m but made w wrong submissions, then his score on that problem is <image>. His total score is equal to the sum of his scores for each problem. In addition, Kevin's total score gets increased by 100 points for each successful hack, but gets decreased by 50 points for each unsuccessful hack.

All arithmetic operations are performed with absolute precision and no rounding. It is guaranteed that Kevin's final score is an integer.

Input

The first line of the input contains five space-separated integers m1, m2, m3, m4, m5, where mi (0 ≤ mi ≤ 119) is the time of Kevin's last submission for problem i. His last submission is always correct and gets accepted.

The second line contains five space-separated integers w1, w2, w3, w4, w5, where wi (0 ≤ wi ≤ 10) is Kevin's number of wrong submissions on problem i.

The last line contains two space-separated integers hs and hu (0 ≤ hs, hu ≤ 20), denoting the Kevin's numbers of successful and unsuccessful hacks, respectively.

Output

Print a single integer, the value of Kevin's final score.

Examples

Input

20 40 60 80 100
0 1 2 3 4
1 0

Output

4900

Input

119 119 119 119 119
0 0 0 0 0
10 0

Output

4930

Note

In the second sample, Kevin takes 119 minutes on all of the problems. Therefore, he gets <image> of the points on each problem. So his score from solving problems is <image>. Adding in 10·100 = 1000 points from hacks, his total score becomes 3930 + 1000 = 4930.

```python
t=list(map(int,input().split()))
w=list(map(int,input().split()))
q,z=map(int,input().split())
c=0
v=0
for i in range(500,3000,500):
  x=(1-(t[v]/250))*i-50*w[v]
  a=max(0.3*i,x)
  c=c+a
  v=v+1
f=q*100-z*50
dp=c+f
print(int(dp))

```


626_D. Jerry's Protest

Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.

Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?

Input

The first line of input contains a single integer n (2 ≤ n ≤ 2000) — the number of balls in the jar.

The second line contains n integers ai (1 ≤ ai ≤ 5000) — the number written on the ith ball. It is guaranteed that no two balls have the same number.

Output

Print a single real value — the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.

Examples

Input

2
1 2

Output

0.0000000000

Input

3
1 2 10

Output

0.0740740741

Note

In the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.

In the second case, each game could've had three outcomes — 10 - 2, 10 - 1, or 2 - 1. Jerry has a higher total if and only if Andrew won 2 - 1 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability <image>.

```python
def main():
    n = int(input())
    a = list(map(int, input().split()))
    max_element = max(a) + 1
    #print(max_element)
    diff_freq = [0 for i in range(max_element)]
    for i in range(n):
        for j in range(i):
            diff_freq[abs(a[i] - a[j])] += 1

    largest = [0 for i in range(max_element)]
    for i in range(max_element - 2, 0, -1):
        largest[i] = largest[i + 1] + diff_freq[i + 1]

    good_ones = 0

    #print('diff_freq', diff_freq)
    #print('largest', largest)

    for i in range(max_element):
        for j in range(max_element):
            if i + j < max_element:
                good_ones += diff_freq[i] * diff_freq[j] * largest[i + j]

    #print(good_ones)
    ans = good_ones / (((n*(n - 1)) / 2) ** 3)
    print(ans)
main()
```


650_B. Image Preview

Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.

For each photo it is known which orientation is intended for it — horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.

Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.

Help Vasya find the maximum number of photos he is able to watch during T seconds.

Input

The first line of the input contains 4 integers n, a, b, T (1 ≤ n ≤ 5·105, 1 ≤ a, b ≤ 1000, 1 ≤ T ≤ 109) — the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.

Second line of the input contains a string of length n containing symbols 'w' and 'h'.

If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.

If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.

Output

Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.

Examples

Input

4 2 3 10
wwhw

Output

2

Input

5 2 4 13
hhwhh

Output

4

Input

5 2 4 1000
hhwhh

Output

5

Input

3 1 100 10
whw

Output

0

Note

In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.

Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.

```python
def main():
    n, a, b, t = map(int, input().split())
    b += 1
    l = [b if char == "w" else 1 for char in input()]
    t -= sum(l) - a * (n + 2)
    hi, n2 = n, n * 2
    n21 = n2 + 1
    lo = res = 0
    l *= 2
    while lo <= n and hi < n2:
        t -= l[hi]
        hi += 1
        b = hi - n
        while lo < b or (hi - lo + (hi if hi < n21 - lo else n21 - lo)) * a > t:
            t += l[lo]
            lo += 1
        if res < hi - lo:
            res = hi - lo
            if res == n:
                break
    print(res)

if __name__ == '__main__':
    main()

```


675_E. Trains and Statistic

Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.

Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≤ i < j ≤ n.

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations.

The second line contains n - 1 integer ai (i + 1 ≤ ai ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to ai inclusive.

Output

Print the sum of ρi, j among all pairs of 1 ≤ i < j ≤ n.

Examples

Input

4
4 4 4

Output

6

Input

5
2 3 5 5

Output

17

Note

In the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.

Consider the second sample:

  * ρ1, 2 = 1
  * ρ1, 3 = 2
  * ρ1, 4 = 3
  * ρ1, 5 = 3
  * ρ2, 3 = 1
  * ρ2, 4 = 2
  * ρ2, 5 = 2
  * ρ3, 4 = 1
  * ρ3, 5 = 1
  * ρ4, 5 = 1

Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.

```python
n=int(input())
a=list(map(int, input().split()))
a=[ai-1 for ai in a]
a[n:n] = [n - 1]

dp=[0]*n
ans=0
i=n-2

nmax=2**17
tree=[[0,0]]*2*nmax;

#Build Segment tree
j=0
while j<n:
    tree[nmax + j] = [a[j], j]
    j=j+1
j=nmax-1
while j>0:
    tree[j]=max(tree[j*2],tree[j*2+1])
    j=j-1

#get max of a interval [left, right]
def get(left, right):
    ans=[-1,-1]
    left=left+nmax
    right=right+nmax+1
    while left<right:
        if (left & 1):
            ans = max(ans, tree[left])
            left = left + 1
        if (right & 1):
            right = right - 1
            ans = max(ans, tree[right])
        left = left // 2
        right = right // 2
    return ans[1]

while i>=0:
    m = get(i + 1, a[i]);
    dp[i] =  dp[m] - (a[i] - m) + n - i - 1
    ans += dp[i]
    i=i-1

print(ans)
```


765_D. Artsem and Saunders

Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem.

Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y.

Now then, you are given a function f: [n] → [n]. Your task is to find a positive integer m, and two functions g: [n] → [m], h: [m] → [n], such that g(h(x)) = x for all <image>, and h(g(x)) = f(x) for all <image>, or determine that finding these is impossible.

Input

The first line contains an integer n (1 ≤ n ≤ 105).

The second line contains n space-separated integers — values f(1), ..., f(n) (1 ≤ f(i) ≤ n).

Output

If there is no answer, print one integer -1.

Otherwise, on the first line print the number m (1 ≤ m ≤ 106). On the second line print n numbers g(1), ..., g(n). On the third line print m numbers h(1), ..., h(m).

If there are several correct answers, you may output any of them. It is guaranteed that if a valid answer exists, then there is an answer satisfying the above restrictions.

Examples

Input

3
1 2 3

Output

3
1 2 3
1 2 3

Input

3
2 2 2

Output

1
1 1 1
2

Input

2
2 1

Output

-1

```python
n = int(input())
f = list(map(int, input().split()))
h = []
ind_h = [-1] * (n + 1)
g = [0] * n
occs = {}
for i in range(len(f)):
    if f[i] not in occs:
        occs[f[i]] = {i + 1}
        h.append(f[i])
        ind_h[f[i]] = len(h) - 1
        g[i] = len(h)
    else:
        g[i] = ind_h[f[i]] + 1
        occs[f[i]].add(i + 1)
for k in occs:
    if k not in occs[k]:
        print(-1)
        exit()
print(len(h))
print(*g)
print(*h)

```


789_A. Anastasia and pebbles

Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.

She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.

Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

Input

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket.

The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

Output

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

Examples

Input

3 2
2 3 4

Output

3

Input

5 4
3 1 8 9 7

Output

5

Note

In the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.

Optimal sequence of actions in the second sample case:

  * In the first day Anastasia collects 8 pebbles of the third type.
  * In the second day she collects 8 pebbles of the fourth type.
  * In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.
  * In the fourth day she collects 7 pebbles of the fifth type.
  * In the fifth day she collects 1 pebble of the second type.

```python
import math

n,k = map(int,input().split())
stones = list(map(int, input().split()))

days = 0
for i in range(n):
    days += math.ceil(stones[i]/k)

print(math.ceil(days/2))
```


80_C. Heroes

The year of 2012 is coming...

According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.

The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: a for Mephisto, b for Diablo and c for Baal.

Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a <image> of experience, rounded down, where x will be the amount of experience for the killed megaboss and y — the number of people in the team.

Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum.

It is known that some heroes like others. But if hero p likes hero q, this does not mean that the hero q likes hero p. No hero likes himself.

The total amount of liking in teams is the amount of ordered pairs (p, q), such that heroes p and q are in the same group, and hero p likes hero q (but it is not important if hero q likes hero p). In case of heroes p and q likes each other and they are in the same group, this pair should be counted twice, as (p, q) and (q, p).

A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.

It is guaranteed that every hero is able to destroy any megaboss alone.

Input

The first line contains a single non-negative integer n (0 ≤ n ≤ 42) — amount of liking between the heroes. Next n lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p ≠  q). Every liking is described in the input exactly once, no hero likes himself.

In the last line are given three integers a, b and c (1 ≤ a, b, c ≤ 2·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal.

In all the pretests, except for examples from the statement, the following condition is satisfied: a = b = c.

Output

Print two integers — the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team).

When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking.

Examples

Input

3
Troll likes Dracul
Dracul likes Anka
Snowy likes Hexadecimal
210 200 180

Output

30 3

Input

2
Anka likes Chapay
Chapay likes Anka
10000 50 50

Output

1950 2

Note

A note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo и Chapay.

```python
# -*- coding: utf-8 -*-
"""
Created on Fri Nov  1 14:28:37 2019

@author: PC-4
"""
from itertools import combinations, product

Teams = [[1, 1, 5],
         [1, 2, 4],
         [1, 3, 3],
         [2, 2, 3]]

Names = {}
Names["Anka"] = 0
Names["Chapay"] = 1
Names["Cleo"] = 2
Names["Dracul"] = 3
Names["Hexadecimal"] = 4
Names["Snowy"] = 5
Names["Troll"] = 6

graph = [[0] * 7 for _ in range(7)]
N = int(input())
for _ in range(N):
    p, q = input().split(" likes ")
    p = Names[p]
    q = Names[q]
    graph[p][q] = 1

a, b, c = sorted(map(int, input().split()))
E_diff_star = float('inf')
team_all = []
for t1, t2, t3 in Teams:
    E = [a//t1, b//t2, c//t3]
    E_diff = max(E) - min(E)
    if E_diff < E_diff_star:
        E_diff_star = E_diff
        team_all = [[t1, t2, t3]]
    elif E_diff == E_diff_star:
        team_all.append([t1, t2, t3])

liking = 0
for team in team_all:
    for te2 in combinations(set(range(7)), team[2]):
        te2 = set(te2)
        left = set(range(7)) - te2
        L2 = sum(graph[p][q] for p, q in product(te2, te2))
        for te1 in combinations(left, team[1]):
            te1 = set(te1)
            te0 = left - te1
            L1 = sum(graph[p][q] for p, q in product(te1, te1))
            L0 = sum(graph[p][q] for p, q in product(te0, te0))
            L = L2 + L1 + L0
            if L > liking:
                liking = L
print(E_diff_star, liking)

```


835_A. Key races

Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 milliseconds.

If connection ping (delay) is t milliseconds, the competition passes for a participant as follows:

  1. Exactly after t milliseconds after the start of the competition the participant receives the text to be entered.
  2. Right after that he starts to type it.
  3. Exactly t milliseconds after he ends typing all the text, the site receives information about it.

The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.

Given the length of the text and the information about participants, determine the result of the game.

Input

The first line contains five integers s, v1, v2, t1, t2 (1 ≤ s, v1, v2, t1, t2 ≤ 1000) — the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.

Output

If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship".

Examples

Input

5 1 2 1 2

Output

First

Input

3 3 1 1 1

Output

Second

Input

4 5 3 1 5

Output

Friendship

Note

In the first example, information on the success of the first participant comes in 7 milliseconds, of the second participant — in 14 milliseconds. So, the first wins.

In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participant — in 5 milliseconds. So, the second wins.

In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participant — in 22 milliseconds. So, it is be a draw.

```python
s, v1, v2, t1, t2 = list(map(int, input().split()))
a = 2*t1 + s*v1
b = 2*t2 + s*v2
if a > b:
    print("Second")
elif a < b:
    print("First")
else:
    print("Friendship")

```


87_B. Vasya and Types

Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.

There is a very powerful system of pointers on &K* — you can add an asterisk to the right of the existing type X — that will result in new type X * . That is called pointer-definition operation. Also, there is the operation that does the opposite — to any type of X, which is a pointer, you can add an ampersand — that will result in a type &X, to which refers X. That is called a dereference operation.

The &K* language has only two basic data types — void and errtype. Also, the language has operators typedef and typeof.

  * The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**.
  * The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.

An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype* = &errtype = errtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.

Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.

Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &T *  is always equal to T.

Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).

Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators.

Input

The first line contains an integer n (1 ≤ n ≤ 100) — the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.

All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.

Output

For every typeof operator print on the single line the answer to that operator — the type that the given operator returned.

Examples

Input

5
typedef void* ptv
typeof ptv
typedef &&ptv node
typeof node
typeof &ptv

Output

void*
errtype
void

Input

17
typedef void* b
typedef b* c
typeof b
typeof c
typedef &b b
typeof b
typeof c
typedef &&b* c
typeof c
typedef &b* c
typeof c
typedef &void b
typeof b
typedef b******* c
typeof c
typedef &&b* c
typeof c

Output

void*
void**
void
void**
errtype
void
errtype
errtype
errtype

Note

Let's look at the second sample.

After the first two queries typedef the b type is equivalent to void*, and с — to void**.

The next query typedef redefines b — it is now equal to &b = &void* = void. At that, the с type doesn't change.

After that the с type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.

Then the b type is again redefined as &void = errtype.

Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef.

```python
types = {'void':'void', 'errtype':'errtype'}

def getRealType(type_expr):

  expr_type = type_expr.strip('&*')

  full_type_name = type_expr.replace(expr_type, types.get(expr_type, "errtype"))

  base_type = full_type_name.strip('&*')

  if base_type == "void":

    addr_count = full_type_name.count('*')

    deref_count = full_type_name.count('&')

    if deref_count > addr_count:

      return "errtype"

    return base_type + "*" * (addr_count - deref_count)

  else:

    return "errtype"

def setTypeAlias(type_expr, alias_name):

  types[alias_name] = getRealType(type_expr)

n = int(input())

for _ in range(n):

  operator = input().split()

  command = operator[0]

  if command == "typedef":

    setTypeAlias(operator[1], operator[2])

  else:

    print(getRealType(operator[1]))

# Made By Mostafa_Khaled
```


903_D. Almost Difference

Let's denote a function

<image>

You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

Input

The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of the array.

Output

Print one integer — the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

Examples

Input

5
1 2 3 1 3

Output

4

Input

4
6 6 5 5

Output

0

Input

4
6 6 4 4

Output

-8

Note

In the first example:

  1. d(a1, a2) = 0;
  2. d(a1, a3) = 2;
  3. d(a1, a4) = 0;
  4. d(a1, a5) = 2;
  5. d(a2, a3) = 0;
  6. d(a2, a4) = 0;
  7. d(a2, a5) = 0;
  8. d(a3, a4) = - 2;
  9. d(a3, a5) = 0;
  10. d(a4, a5) = 2.

```python
from sys import stdin, stdout
n = int(stdin.readline())
a = [int(i) for i in stdin.readline().split()]
d = dict()
ans, sm = 0, 0
for i in range(n):
    if a[i] not in d.keys():
        d[a[i]] = 0
    d[a[i]] += 1
    ans += i * a[i] - sm
    if (a[i] + 1) in d.keys():
        ans += 1 * d[a[i] + 1]
    if (a[i] - 1) in d.keys():
        ans -= 1 * d[a[i] - 1]
    sm += a[i]
stdout.write(str(ans))

```


954_F. Runner's Problem

You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column.

You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to:

  * (i - 1, j + 1) — only if i > 1,
  * (i, j + 1), or
  * (i + 1, j + 1) — only if i < 3.

However, there are n obstacles blocking your path. k-th obstacle is denoted by three integers ak, lk and rk, and it forbids entering any cell (ak, j) such that lk ≤ j ≤ rk.

You have to calculate the number of different paths from (2, 1) to (2, m), and print it modulo 109 + 7.

Input

The first line contains two integers n and m (1 ≤ n ≤ 104, 3 ≤ m ≤ 1018) — the number of obstacles and the number of columns in the matrix, respectively.

Then n lines follow, each containing three integers ak, lk and rk (1 ≤ ak ≤ 3, 2 ≤ lk ≤ rk ≤ m - 1) denoting an obstacle blocking every cell (ak, j) such that lk ≤ j ≤ rk. Some cells may be blocked by multiple obstacles.

Output

Print the number of different paths from (2, 1) to (2, m), taken modulo 109 + 7. If it is impossible to get from (2, 1) to (2, m), then the number of paths is 0.

Example

Input

2 5
1 3 4
2 2 3

Output

2

```python
from operator import itemgetter
import sys
input = sys.stdin.buffer.readline

def _mul(A, B, MOD):
    C = [[0] * len(B[0]) for i in range(len(A))]
    for i in range(len(A)):
        for k in range(len(B)):
            for j in range(len(B[0])):
                C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD
    return C

def pow_matrix(A, n, MOD):
    B = [[0] * len(A) for i in range(len(A))]
    for i in range(len(A)):
        B[i][i] = 1
    while n > 0:
        if n & 1:
            B = _mul(A, B, MOD)
        A = _mul(A, A, MOD)
        n  = n // 2
    return B

def calc(A, vec, MOD):
    n = len(vec)
    res = [0] * n
    for i in range(n):
        for j in range(n):
            res[i] += A[i][j] * vec[j]
            res[i] %= MOD
    return res

n, m = map(int, input().split())
info = [list(map(int, input().split())) for i in range(n)]
MOD = 10 ** 9 + 7

res = [[] for i in range(3)]
for row, l, r in info:
    row -= 1
    l -= 1
    res[row].append((l, r))
for row in range(3):
    res[row].sort(key=itemgetter(1))

blocks = {}
ind_set = set([])
for row in range(3):
    tmp = []
    for l, r in res[row]:
        if not tmp:
            tmp.append((l, r))
            continue
        while tmp:
            if l <= tmp[-1][1]:
                pl, pr = tmp.pop()
                l = min(pl, l)
            else:
                break
        tmp.append((l, r))
    for l, r in tmp:
        if l not in blocks:
            blocks[l] = []
        if r not in blocks:
            blocks[r] = []
        blocks[l].append((row, 1))
        blocks[r].append((row, -1))
        ind_set.add(l)
        ind_set.add(r)

ind_list = sorted(list(ind_set))

dp = [0, 1, 0]
matrix = [[1, 1, 0], [1, 1, 1], [0, 1, 1]]

prv_ind = 0
for ind in ind_list:
    length = (ind - prv_ind - 1)
    tmp_matrix = pow_matrix(matrix, length, MOD)
    dp = calc(tmp_matrix, dp, MOD)

    for row, flag in blocks[ind]:
        if flag == 1:
            for i in range(3):
                matrix[row][i] = 0
        else:
            for i in range(3):
                matrix[row][i] = 1
            matrix[0][2] = 0
            matrix[2][0] = 0
    dp = calc(matrix, dp, MOD)
    prv_ind = ind

length = m - prv_ind - 1
tmp_matrix = pow_matrix(matrix, length, MOD)
dp = calc(tmp_matrix, dp, MOD)

print(dp[1] % MOD)
```


9_E. Interesting Graph and Apples

Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.

She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive.

Input

The first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.

Output

In the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero.

Examples

Input

3 2
1 2
2 3

Output

YES
1
1 3

```python
def dfs(v, comp):
    used[v] = comp
    for u in graph[v]:
        if not used[u]:
            dfs(u, comp)

n, m = map(int, input().split())
graph = [[] for i in range(n)]
for i in range(m):
    v, u = map(int, input().split())
    graph[v - 1].append(u - 1)
    graph[u - 1].append(v - 1)
used = [0] * n
ncomp = 0
for v in range(n):
    if not used[v]:
        ncomp += 1
        dfs(v, ncomp)
maxpwr = max(map(len, graph))
if n - m != ncomp or maxpwr > 2:
    if n == m and ncomp == 1 and maxpwr == 2:
        print("YES")
        print(0)
    else:
        print("NO")
else:
    print("YES")
    print(n - m)
    leaves = []
    for v in range(n):
        if len(graph[v]) == 1:
            leaves.append([v + 1, used[v]])
        elif len(graph[v]) == 0:
            leaves.append([v + 1, used[v]])
            leaves.append([v + 1, used[v]])
    sets = []
    for i in range(len(leaves)):
        if leaves[i][0] == 0:
            continue
        for j in range(i + 1, len(leaves)):
            if leaves[j][0] == 0:
                continue
            if leaves[i][1] == leaves[j][1]:
                continue
            seti = -1
            for k in range(len(sets)):
                if leaves[i][1] in sets[k]:
                    seti = k
                    break
            setj = -2
            for k in range(len(sets)):
                if leaves[j][1] in sets[k]:
                    setj = k
                    break
            if seti != setj:
                print(leaves[i][0], leaves[j][0])
                if seti >= 0:
                    if setj >= 0:
                        sets[seti] |= sets[setj]
                        sets.pop(setj)
                    else:
                        sets[seti].add(leaves[j][1])
                else:
                    if setj >= 0:
                        sets[setj].add(leaves[i][1])
                    else:
                        sets.append(set([leaves[i][1], leaves[j][1]]))
                leaves[i][0] = 0
                leaves[j][0] = 0
                break
    for i in range(len(leaves)):
        if leaves[i][0] == 0:
            continue
        for j in range(i + 1, len(leaves)):
            if leaves[j][0] == 0:
                continue
            print(leaves[i][0], leaves[j][0])
            break
        else:
            continue
        break
```


p02548 AtCoder Beginner Contest 179 - A x B + C

Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

* 2 \leq N \leq 10^6
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Examples

Input

3

Output

3

Input

100

Output

473

Input

1000000

Output

13969985

```python
N = int(input())
ans = 0
for i in range(1, N):
    ans += (N - 1) // i
print(ans)
```


p02679 AtCoder Beginner Contest 168 - ∙ (Bullet)

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

* All values in input are integers.
* 1 \leq N \leq 2 \times 10^5
* -10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Examples

Input

3
1 2
-1 1
2 -1

Output

5

Input

10
3 2
3 2
-1 1
2 -1
-3 -9
-8 12
7 7
8 1
8 2
8 4

Output

479

```python
from collections import defaultdict

def gcd(a, b):
    return gcd(b, a%b) if b else a

mod = 10 ** 9 + 7
N = int(input())
X = defaultdict(lambda: [0, 0])
# X = dict()
x = 0
y = 0
z = 0
for i in range(N):
    a, b = map(int, input().split())
    g = abs(gcd(a, b))
    if a * b > 0:
        X[(abs(a) // g, abs(b) // g)][0] += 1
    elif a * b < 0:
        X[(abs(b) // g, abs(a) // g)][1] += 1
    else:
        if a:
            x += 1
        elif b:
            y += 1
        else:
            z += 1
# suppose we have a super head point which can put togother with every point.
ans = 1
pow2 = [1]
for i in range(N):
    pow2 += [pow2[-1] * 2 % mod]
for i in X.values():
    ans *= pow2[i[0]] + pow2[i[1]]- 1
    ans %= mod
ans *= pow2[x] + pow2[y] - 1
print((ans+z-1)%mod)

```


p02807 Dwango Programming Contest 6th - Fusing Slimes

There are N slimes standing on a number line. The i-th slime from the left is at position x_i.

It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}.

Niwango will perform N-1 operations. The i-th operation consists of the following procedures:

* Choose an integer k between 1 and N-i (inclusive) with equal probability.
* Move the k-th slime from the left, to the position of the neighboring slime to the right.
* Fuse the two slimes at the same position into one slime.

Find the total distance traveled by the slimes multiplied by (N-1)! (we can show that this value is an integer), modulo (10^{9}+7). If a slime is born by a fuse and that slime moves, we count it as just one slime.

Constraints

* 2 \leq N \leq 10^{5}
* 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}
* x_i is an integer.

Input

Input is given from Standard Input in the following format:

N
x_1 x_2 \ldots x_N

Output

Print the answer.

Examples

Input

3
1 2 3

Output

5

Input

12
161735902 211047202 430302156 450968417 628894325 707723857 731963982 822804784 880895728 923078537 971407775 982631932

Output

750927044

```python
n = int(input())
lst1 = list(map(int,input().split()))
mod = 10**9+7
def pow(n, p):
    res = 1
    while p > 0:
        if p % 2 == 0:
            n = n ** 2 % mod
            p //= 2
        else:
            res = res * n % mod
            p -= 1
    return res % mod
fac = [1]

for i in range(n-1):
    fac.append(fac[-1]*(i+1)%mod)

f = 1
ans = 0
for i in range(n-1):
    ans += ((lst1[-1]-lst1[i])*fac[-1]*pow(i+1,mod-2))%mod
print(ans%mod)
```


p02943 AtCoder Grand Contest 037 - Reversing and Concatenating

Takahashi has a string S of length N consisting of lowercase English letters. On this string, he will perform the following operation K times:

* Let T be the string obtained by reversing S, and U be the string obtained by concatenating S and T in this order.
* Let S' be some contiguous substring of U with length N, and replace S with S'.

Among the strings that can be the string S after the K operations, find the lexicographically smallest possible one.

Constraints

* 1 \leq N \leq 5000
* 1 \leq K \leq 10^9
* |S|=N
* S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the lexicographically smallest possible string that can be the string S after the K operations.

Examples

Input

5 1
bacba

Output

aabca

Input

10 2
bbaabbbaab

Output

aaaabbaabb

```python
def solve(n, k, s):
    u = s + s[::-1]
    t = min(u[i:i + n] for i in range(n + 1))
    i, h = 0, t[0]
    for i, c in enumerate(t):
        if c != h:
            break
    j = i
    for _ in range(k - 1):
        j <<= 1
        if j >= n:
            return h * n
    return h * j + t[i:i + n - j]

n, k = map(int, input().split())
s = input()
print(solve(n, k, s))

```


p03080 ExaWizards 2019 - Red or Blue

There are N people numbered 1 to N. Each person wears a red hat or a blue hat.

You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

* 1 \leq N \leq 100
* |s| = N
* s_i is `R` or `B`.

Input

Input is given from Standard Input in the following format:

N
s

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print `Yes`; otherwise, print `No`.

Examples

Input

4
RRBR

Output

Yes

Input

4
BRBR

Output

No

```python
n = input()
s = input()

if s.count('R') > s.count('B') :
    print('Yes')
else :
    print('No')

```


p03225 Tenka1 Programmer Contest - Equilateral

There are some coins in the xy-plane. The positions of the coins are represented by a grid of characters with H rows and W columns. If the character at the i-th row and j-th column, s_{ij}, is `#`, there is one coin at point (i,j); if that character is `.`, there is no coin at point (i,j). There are no other coins in the xy-plane.

There is no coin at point (x,y) where 1\leq i\leq H,1\leq j\leq W does not hold. There is also no coin at point (x,y) where x or y (or both) is not an integer. Additionally, two or more coins never exist at the same point.

Find the number of triples of different coins that satisfy the following condition:

* Choosing any two of the three coins would result in the same Manhattan distance between the points where they exist.

Here, the Manhattan distance between points (x,y) and (x',y') is |x-x'|+|y-y'|. Two triples are considered the same if the only difference between them is the order of the coins.

Constraints

* 1 \leq H,W \leq 300
* s_{ij} is `#` or `.`.

Input

Input is given from Standard Input in the following format:

H W
s_{11}...s_{1W}
:
s_{H1}...s_{HW}

Output

Print the number of triples that satisfy the condition.

Examples

Input

5 4
#.##
.##.
#...
..##
...#

Output

3

Input

5 4
.##
.##.
...
..##
...#

Output

3

Input

13 27
......#.........#.......#..
...#.....###..
..............#####...##...
...#######......#...#######
...#.....#.....###...#...#.
...#######....#.#.#.#.###.#
..............#.#.#...#.#..
.#.#.#...###..
...........#...#...#######
..#######..#...#...#.....#
..#.....#..#...#...#.###.#
..#######..#...#...#.#.#.#
..........##...#...#.#####

Output

870

```python
H,W=map(int,input().split())
S=[list(input()) for i in range(H)]
table=[[0]*(H+W-1) for i in range(H+W-1)]
for j in range(H):
    for i in range(W):
        if S[j][i]=='#':
            table[i+j][i-j+H-1]=1
yoko=[[0]*(H+W) for i in range(H+W-1)]
for j in range(H+W-1):
    for i in range(1,H+W):
            yoko[j][i]=yoko[j][i-1]+table[j][i-1]
tate=[[0]*(H+W-1) for i in range(H+W)]
for j in range(1,H+W):
    for i in range(H+W-1):
        tate[j][i]=tate[j-1][i]+table[j-1][i]

ans=0
for y in range(H+W-1):
    for x in range((y+H-1)%2,H+W-1,2):
        if table[y][x]!=1:
            continue
        for z in range(x+2,H+W-1,2):
            if table[y][z]==1:
                d=z-x
                if y+d<H+W-1:
                    ans+=yoko[y+d][z+1]-yoko[y+d][x]
                    #print(1,'.',ans,':',x,y,z)
                if y-d>=0:
                    ans+=yoko[y-d][z+1]-yoko[y-d][x]
                    #print(2,'.',ans,':',x,y,z)
        for w in range(y+2,H+W-1,2):
            if table[w][x]==1:
                e=w-y
                if x+e<H+W-1:
                    ans+=tate[w][x+e]-tate[y+1][x+e]
                    #print(3,'.',ans,':',x,y,w)
                if x-e>=0:
                    ans+=tate[w][x-e]-tate[y+1][x-e]
                    #print(4,'.',ans,':',x,y,w)

print(ans)

```


p03371 AtCoder Beginner Contest 095 - Half and Half

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

* 1 ≤ A, B, C ≤ 5000
* 1 ≤ X, Y ≤ 10^5
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Examples

Input

1500 2000 1600 3 2

Output

7900

Input

1500 2000 1900 3 2

Output

8500

Input

1500 2000 500 90000 100000

Output

100000000

```python
a, b, c, x, y = map(int, input().split())
print(min(a*x+b*y, c*2*max(x,y), c*2*min(x,y)+abs(x-y)*(a if x>y else b)))
```


p03534 CODE FESTIVAL 2017 Final (Parallel) - Palindrome-phobia

Snuke has a string S consisting of three kinds of letters: `a`, `b` and `c`.

He has a phobia for palindromes, and wants to permute the characters in S so that S will not contain a palindrome of length 2 or more as a substring. Determine whether this is possible.

Constraints

* 1 \leq |S| \leq 10^5
* S consists of `a`, `b` and `c`.

Input

Input is given from Standard Input in the following format:

S

Output

If the objective is achievable, print `YES`; if it is unachievable, print `NO`.

Examples

Input

abac

Output

YES

Input

aba

Output

NO

Input

babacccabab

Output

YES

```python
s=input()
from collections import defaultdict
d=defaultdict(int)
for c in s:
  d[c]+=1
a,b,c=d["a"],d["b"],d["c"]
mx=max(a,b,c)
mn=min(a,b,c)
#a,b,c = map(lambda x:x-mn, [a,b,c])
if mx-mn >=2:
  print("NO")
else:
  print("YES")
```


p03694 AtCoder Beginner Contest 064 - Traveling AtCoDeer Problem

It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.
There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.
Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.

Constraints

* 1 ≤ N ≤ 100
* 0 ≤ a_i ≤ 1000
* a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum distance to be traveled.

Examples

Input

4
2 3 7 9

Output

7

Input

8
3 1 4 1 5 9 2 6

Output

8

```python
num = input()
l = list(map(int, input().split()))

print(max(l) - min(l))
```


p03849 AtCoder Regular Contest 066 - Xor Sum

You are given a positive integer N. Find the number of the pairs of integers u and v (0≦u,v≦N) such that there exist two non-negative integers a and b satisfying a xor b=u and a+b=v. Here, xor denotes the bitwise exclusive OR. Since it can be extremely large, compute the answer modulo 10^9+7.

Constraints

* 1≦N≦10^{18}

Input

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

N

Output

Print the number of the possible pairs of integers u and v, modulo 10^9+7.

Examples

Input

3

Output

5

Input

1422

Output

52277

Input

1000000000000000000

Output

787014179

```python
n=int(input())
d=dict()
def get(n):
    if(n==1):return 1
    if(n==0):return 0
    if(n in d.keys()):return d[n]
    if(n%2==0):
        d[n]=2*get(n//2)+get(n//2-1)
    else:
        d[n]=2*get(n//2)+get(n//2+1)
    d[n]%=(10**9+7)
    return d[n]
def check(u,v,n):
    for a in range(n+1):
        b=u ^ a
        if(a+b==v):
            return 1
    return 0
#for e in range(1,n):
#    ans=0
#    for i in range(e+1):
##        for j in range(e+1):
#            ans+=check(i,j,e)
#    print(ans,get(e+1))
print(get(n+1))

```


p04015 AtCoder Regular Contest 060 - Tak and Cards

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i. He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A. In how many ways can he make his selection?

Constraints

* 1 \leq N \leq 50
* 1 \leq A \leq 50
* 1 \leq x_i \leq 50
* N,\,A,\,x_i are integers.

Input

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

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Examples

Input

4 8
7 9 8 9

Output

5

Input

3 8
6 6 9

Output

0

Input

8 5
3 6 2 8 7 6 5 9

Output

19

Input

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Output

8589934591

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

dp=[[[0]*(sum(X)+1) for _ in range(n+1)] for _ in range(n+1)]

dp[0][0][0]=1

for i in range(1,n+1): #x_1,x_2...x_n
  for k in range(i):   #k枚数選ぶ
    for s in range(sum(X)+1): #合計
      if dp[i-1][k][s]:
        dp[i][k+1][s+X[i-1]]+=dp[i-1][k][s] #1枚選択肢が増えた時の、そのカードを加えた結果を加算
        dp[i][k][s]+=dp[i-1][k][s]
ans=0
for i in range(1,n+1):
  for j in range(1,sum(X)+1):
    if j == i*a: #合計が平均のi倍の時に加える
      ans+=dp[n][i][j]

print(ans)
```