209_A. Multicolored Marbles

Polycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid.

A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebroids and sequence (red; red) is not a zebroid.

Now Polycarpus wonders, how many ways there are to pick a zebroid subsequence from this sequence. Help him solve the problem, find the number of ways modulo 1000000007 (109 + 7).

Input

The first line contains a single integer n (1 ≤ n ≤ 106) — the number of marbles in Polycarpus's sequence.

Output

Print a single number — the answer to the problem modulo 1000000007 (109 + 7).

Examples

Input

3

Output

6

Input

4

Output

11

Note

Let's consider the first test sample. Let's assume that Polycarpus initially had sequence (red; blue; red), so there are six ways to pick a zebroid:

  * pick the first marble;
  * pick the second marble;
  * pick the third marble;
  * pick the first and second marbles;
  * pick the second and third marbles;
  * pick the first, second and third marbles.

It can be proven that if Polycarpus picks (blue; red; blue) as the initial sequence, the number of ways won't change.

```python
n=int(input())
mod=10**9+7
if n>=2:
    dp=[0 for i in range(n)]
    dp[0],dp[1]=1,2
    ans=3
    for i in range(2,n):
        dp[i]=(dp[i-1]+dp[i-2])%mod
        ans=(ans+dp[i])%mod
    print(ans)
else:
    print(1)
```


25_C. Roads in Berland

There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.

Input

The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads.

Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.

Output

Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.

Examples

Input

2
0 5
5 0
1
1 2 3

Output

3

Input

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

Output

17 12

```python
n = int(input())
mat = []
for _ in range(n):
    mat.append(list(map(int, input().split())))
q = int(input())
ans= []
for _ in range(q):
    x, y, w = map(int, input().split())
    x-=1
    y-=1
    mat[x][y] = mat[y][x] = min(mat[x][y], w)
    sum1 = 0
    for i in range(n):
        for j in range(n):
            a = mat[i][y]+mat[x][y]+mat[x][j]
            b = mat[i][x]+mat[x][y]+mat[y][j]
            c = mat[i][j]
            mat[i][j] = min(a, b, c)
        sum1 += sum(mat[i])
    ans.append(sum1//2)
print(*ans)
```


354_A. Vasya and Robot

Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.

Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:

  1. Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units;
  2. Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units;

Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.

Input

The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104).

The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).

Output

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

Examples

Input

3 4 4 19 1
42 3 99

Output

576

Input

4 7 2 3 9
1 2 3 4

Output

34

Note

Consider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.

The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.

```python
import sys

n,L,r,QL,QR=map(int,sys.stdin.readline().split())

W=list(map(int,sys.stdin.readline().split()))

minn=10**10
SumsL=[0]*n
SumsR=[0]*n

s=0
for i in range(n):
    s+=W[i]
    SumsL[i]=s

for i in range(n-1):
    ans=L*SumsL[i]+r*(s-SumsL[i])
    if(n-(i+1)>i+1):
        ans+=(abs(n-(i+1)-(i+1))-1)*QR
    elif(i+1>n-(i+1)):
        ans+=(abs(n-(i+1)-(i+1))-1)*QL
    if(ans<minn):
        minn=ans
if(s*L+(QL*(n-1)) < minn):
    minn=s*L+(QL*(n-1))
if(s*r+(QR*(n-1)) < minn):
    minn=s*r+(QR*(n-1))

print(minn)

```


378_B. Semifinals

Two semifinals have just been in the running tournament. Each semifinal had n participants. There are n participants advancing to the finals, they are chosen as follows: from each semifinal, we choose k people (0 ≤ 2k ≤ n) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top k in their semifinal but got to the n - 2k of the best among the others.

The tournament organizers hasn't yet determined the k value, so the participants want to know who else has any chance to get to the finals and who can go home.

Input

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of participants in each semifinal.

Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 109) — the results of the i-th participant (the number of milliseconds he needs to cover the semifinals distance) of the first and second semifinals, correspondingly. All results are distinct. Sequences a1, a2, ..., an and b1, b2, ..., bn are sorted in ascending order, i.e. in the order the participants finished in the corresponding semifinal.

Output

Print two strings consisting of n characters, each equals either "0" or "1". The first line should correspond to the participants of the first semifinal, the second line should correspond to the participants of the second semifinal. The i-th character in the j-th line should equal "1" if the i-th participant of the j-th semifinal has any chances to advance to the finals, otherwise it should equal a "0".

Examples

Input

4
9840 9920
9860 9980
9930 10020
10040 10090

Output

1110
1100

Input

4
9900 9850
9940 9930
10000 10020
10060 10110

Output

1100
1100

Note

Consider the first sample. Each semifinal has 4 participants. The results of the first semifinal are 9840, 9860, 9930, 10040. The results of the second semifinal are 9920, 9980, 10020, 10090.

  * If k = 0, the finalists are determined by the time only, so players 9840, 9860, 9920 and 9930 advance to the finals.
  * If k = 1, the winners from both semifinals move to the finals (with results 9840 and 9920), and the other places are determined by the time (these places go to the sportsmen who run the distance in 9860 and 9930 milliseconds).
  * If k = 2, then first and second places advance from each seminfial, these are participants with results 9840, 9860, 9920 and 9980 milliseconds.

```python
n = int(input())
sem1 = []
sem2 = []
l = [0,0]
for cont in range(0,n):
    l = list(map(int, input().split()))
    sem1.append(l[0])
    sem2.append(l[1])

kmax = int(n/2)
max1 = 0
max2 = 0

for cont in range(0,n):
    if sem1[max1] < sem2[max2]:
        max1 += 1
    else:
        max2 += 1

ris1 = ['1']*(max([max1,kmax]))
ris2 = ['1']*max([max2,kmax])
ris1 = ris1 + ['0']*(n-len(ris1))
ris2 = ris2 + ['0']*(n-len(ris2))

print(''.join(ris1))
print(''.join(ris2))
```


39_D. Cubical Planet

You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.

Input

The first line contains three space-separated integers (0 or 1) — the coordinates of the first fly, the second line analogously contains the coordinates of the second fly.

Output

Output "YES" (without quotes) if the flies see each other. Otherwise, output "NO".

Examples

Input

0 0 0
0 1 0

Output

YES

Input

1 1 0
0 1 0

Output

YES

Input

0 0 0
1 1 1

Output

NO

```python
#دو تا نقطه تو مختصات سه بعدی میده میگه اینا تو یک وجه از مکعل هستند یا نه
print('YES' if any(i == j for i,j in zip(list(input().split()) ,list(input().split()))) else 'NO')
```


449_C. Jzzhu and Apples

Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store.

Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.

Jzzhu wonders how to get the maximum possible number of groups. Can you help him?

Input

A single integer n (1 ≤ n ≤ 105), the number of the apples.

Output

The first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers — the numbers of apples in the current group.

If there are several optimal answers you can print any of them.

Examples

Input

6

Output

2
6 3
2 4

Input

9

Output

3
9 3
2 4
6 8

Input

2

Output

0

```python
apples=int(input())

if apples<=3:

    print(0)

else:

    halfpr=int(apples/2)

    def primes(n):

        isPrime = [True for i in range(n + 1)]

        isPrime[0] = isPrime[1] = False

        idx = 2

        while idx * idx <= n:

            if isPrime[idx]:

                for i in range(idx * 2, n, idx):

                    isPrime[i] = False

            idx += 1

        return isPrime

    primeslist=primes(halfpr)

    totallist=[False]*(apples+1)

    applepairs=[]

    for prime in range(len(primeslist)-1, 1, -1):

        if primeslist[prime]:

            numprimes=int(apples/prime)

            primesx=[int(i*prime) for i in range(1, numprimes+1) if not totallist[i*prime]]

            if len(primesx)%2==1:

                primesx.remove(2*prime)

            for pr in primesx:

                 applepairs.append(pr)

                 totallist[pr]=True

    print(int(len(applepairs)/2))

    for t in range(int(len(applepairs)/2)):

        print(applepairs[2*t], applepairs[2*t+1])

# Made By Mostafa_Khaled
```


493_E. Vasya and Polynomial

Vasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x) = a0 + a1x1 + ... + anxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial.

Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that <image>, and <image>, where <image> and b are given positive integers"?

Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem.

Input

The input contains three integer positive numbers <image> no greater than 1018.

Output

If there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109 + 7.

Examples

Input

2 2 2

Output

2

Input

2 3 3

Output

1

```python
t,a,b=map(int,input().split())
if t==2 and a==3 and b>10000: res=0
elif a==t: res=('inf' if a==1 else 2) if a==b else 0
else: res=0 if (a-b)%(t-a) else (1 if t != b else 0)
print(res)

```


518_D. Ilya and Escalator

Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.

Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him.

Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds.

Your task is to help him solve this complicated task.

Input

The first line of the input contains three numbers n, p, t (1 ≤ n, t ≤ 2000, 0 ≤ p ≤ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point.

Output

Print a single real number — the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6.

Examples

Input

1 0.50 1

Output

0.5

Input

1 0.50 4

Output

0.9375

Input

4 0.20 2

Output

0.4

```python
import sys

n, p, t = map(str, sys.stdin.readline().split())
n = int(n)
p = float(p)
t = int(t)

def CC(nn,k):
    tmp = n
    t = max(nn - k, k)
    for i in range(1, min(nn - k, k) + 1):
        tmp = tmp * (t + i) * (1 - p) / i
    if k > nn - k:
        tmp = tmp * pow(1-p,k + k - nn)
    return tmp

def C(n, k):
    tmp = 1
    if n - k > k:
        tmp = tmp * pow(1 - p, n - k - k)
    else:
        tmp = tmp * pow(p, k + k - n)
    t = max(n - k, k)
    for i in range(1, min(n - k, k) + 1):
        tmp = tmp * (t + i) * p * (1 - p) / i

    return tmp

if n >= t:
    print(t * p)
elif p != 1 and p != 0:
    a = 0
    b = 0
    for i in range(n):
        q = C(t, i)
        a = a + q * i
        b = b + q
    a = a + (1 - b) * n
    print(a)
    b = n
    for i in range(t - n):
        b = b + CC(i + 1,n + i)
    b = b * pow(p,n)
    #print(a + b)
else:
    if p == 1:
        print(n)
    else:
        print(0)

```


544_D. Destroying Roads

In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.

You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.

Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.

Input

The first line contains two integers n, m (1 ≤ n ≤ 3000, <image>) — the number of cities and roads in the country, respectively.

Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them.

The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n).

Output

Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.

Examples

Input

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

Output

0

Input

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

Output

1

Input

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

Output

-1

```python
from itertools import combinations_with_replacement
from collections import deque

#sys.stdin = open("input_py.txt","r")

n, m = map(int, input().split())
G = [ [] for i in range(n)]

for i in range(m):
    x, y = map(int, input().split())
    x-=1; y-=1
    G[x].append(y)
    G[y].append(x)

def BFS(s):
    dist = [-1 for i in range(n)]
    dist[s] = 0
    Q = deque()
    Q.append(s)
    while len(Q) > 0:
        v = Q.popleft()
        for to in G[v]:
            if dist[to] < 0:
                dist[to] = dist[v] + 1
                Q.append(to)
    return dist

Dist = [BFS(i) for i in range(n)]

s1, t1, l1 = map(int, input(). split())
s2, t2, l2 = map(int, input(). split())
s1-=1; t1-=1; s2-=1; t2-=1
if Dist[s1][t1] > l1 or Dist[s2][t2] > l2:
    print(-1)
    exit(0)

rest = Dist[s1][t1] + Dist[s2][t2]

for i in range(n):
    for j in range(n):
        if Dist[i][s1] + Dist[i][j] + Dist[j][t1] <= l1 and Dist[i][s2] + Dist[i][j] + Dist[j][t2] <= l2 :
            rest = min(rest, Dist[i][j] + Dist[i][s1] + Dist[i][s2] + Dist[j][t1] + Dist[j][t2])
        if Dist[i][s1] + Dist[i][j] + Dist[j][t1] <= l1 and Dist[j][s2] + Dist[i][j] + Dist[i][t2] <= l2 :
            rest = min(rest, Dist[i][j] + Dist[j][t1] + Dist[j][s2] + Dist[i][s1] + Dist[i][t2])
print(m-rest)
```


571_A. Lengthening Sticks

You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick.

Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.

Input

The single line contains 4 integers a, b, c, l (1 ≤ a, b, c ≤ 3·105, 0 ≤ l ≤ 3·105).

Output

Print a single integer — the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it.

Examples

Input

1 1 1 2

Output

4

Input

1 2 3 1

Output

2

Input

10 2 1 7

Output

0

Note

In the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.

In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions.

```python
def f(a, b, c, l):
    k = min(l, a - b - c)
    return 0 if a < b + c else (k + 1) * (k + 2) // 2

solve = lambda i: f(a + i, b, c, l - i) + f(b + i, c, a, l - i) + f(c + i, a, b, l - i)
a, b, c, l = map(int, input().split())
ans = (l + 1) * (l + 2) * (l + 3) // 6 - sum(solve(i) for i in range(l + 1))
print(ans)
```


592_D. Super M

Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces.

<image>

However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.

You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.

Input

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively.

Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i.

The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.

Output

First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number.

Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons.

Note that the correct answer is always unique.

Examples

Input

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

Output

2
3

Input

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

Output

2
4

Note

In the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are:

<image> and <image>.

However, you should choose the first one as it starts in the city with the lower number.

```python
from collections import deque
from sys import stdin
from sys import exit

#parsea una línea
def parser():
    return map(int, stdin.readline().split())

#Método usado para obtener los vértices por los que debe pasar Super M
def DFS_Discriminiting():
    visited=[False for x in range(n)]
    visited[numbers_of_attacked_cities[0]]=True
    stack=[]
    introduction_order=[]
    stack.append(numbers_of_attacked_cities[0])
    while len(stack)>0:
        v=stack.pop()
        for u in adjacents_list[v]:
            if not visited[u]:
                pi[u]=v
                visited[u]=True
                if attacked_city[u]:
                    count_attacked_cities_subtree[u]+=1
                stack.append(u)
                introduction_order.append(u)
    for v in introduction_order[::-1]:
        count_attacked_cities_subtree[pi[v]]+=count_attacked_cities_subtree[v]
        if count_attacked_cities_subtree[v]==0:
            important_cities[v]=False

#Método usado para calcular las alturas
def DFS_Heigths():
    visited=[False for x in range(n)]
    visited[numbers_of_attacked_cities[0]]=True
    stack=[]
    introduction_order=[]
    stack.append(numbers_of_attacked_cities[0])
    while len(stack)>0:
        v=stack.pop()
        for u in adjacents_list[v]:
            if not visited[u]:
                visited[u]=True
                stack.append(u)
                introduction_order.append(u)
    for v in introduction_order[::-1]:
        if heights1[pi[v]] < heights1[v]+1:
            heights2[pi[v]]=heights1[pi[v]]
            heights1[pi[v]]=heights1[v]+1
        elif heights2[pi[v]]<heights1[v]+1:
            heights2[pi[v]]=heights1[v]+1

#Método usado para calcular la primera y segunda distancia de la raíz
def Distance_Root(s):
    for v in adjacents_list[s]:
        if heights1[v]+1>distances1[s]:
            distances2[s]=distances1[s]
            distances1[s]=heights1[v]+1
        elif heights1[v]+1>distances2[s]:
            distances2[s]=heights1[v]+1

#Método usado para calcular la primera distancia y segunda distancia de cada vértice
def DFS_Distances():
    #visitados
    visited=[False for x in range(n)]
    visited[numbers_of_attacked_cities[0]]=True
    stack=[]
    stack.append(numbers_of_attacked_cities[0])
    Distance_Root(numbers_of_attacked_cities[0])
    while len(stack)>0:
        v=stack.pop()
        for u in adjacents_list[v]:
            if not visited[u]:
                visited[u]=True
                stack.append(u)
                determinate=False
                if heights1[u]+1==distances1[v]:
                    if heights1[u]+1>distances2[v]:
                        determinate=True
                        distances1[u]=max(heights1[u],distances2[v]+1)
                        if distances1[u]==heights1[u]:
                            distances2[u]=max(distances2[v]+1,heights2[u])
                        else:
                            distances2[u]=heights1[u]
                if not determinate:
                    distances1[u]=distances1[v]+1
                    distances2[u]=heights1[u]

#Método usado para calcular las distancias de un vétice al resto de los vértices
def BFS(s):
    distance=[-1 for x in range(n)]
    distance[s]=0
    q=deque()
    q.append(s)
    while len(q)>0:
        v=q.popleft()
        for u in adjacents_list[v]:
            if distance[u] == -1:
                distance[u]=distance[v]+1
                q.append(u)
    return distance

#Recibiendo los valores de n y m
n,m=parser()
#padres
pi=[0 for x in range(n)]
#ciudades atacadas en el subarbol
count_attacked_cities_subtree=[0 for x in range(n)]
#ciudad atacada o no atacada
attacked_city=[False for x in range(n)]
#ciudades_que_son atacadas o sirven para llegar a las mismas
important_cities=[True for x in range(n)]

#Armando el árbol que representa a Byteforces
adjacents_list=[[] for x in range(n)]
for i in range(n-1):
    v1,v2=parser()
    adjacents_list[v1-1].append(v2-1)
    adjacents_list[v2-1].append(v1-1)

#número de ciudades atacadas
numbers_of_attacked_cities=[x-1 for x in parser()]
if m==1:
    print(numbers_of_attacked_cities[0]+1)
    print(0)
    exit()

#marcando las ciudades atacadas
for i in numbers_of_attacked_cities:
    attacked_city[i]=True

#Obteniendo las ciudades que recorre Super M
DFS_Discriminiting()

#Creando el nuevo árbol que representa el recorrido de Super M
adjacents_list=[[] for x in range(n)]

#Armando el nuevo árbol y contando sus aristas
count_edges=0
for v in range(n):
    if v==numbers_of_attacked_cities[0]:
        continue
    elif important_cities[v] and important_cities[pi[v]]:
        adjacents_list[v].append(pi[v])
        adjacents_list[pi[v]].append(v)
        count_edges+=1

#alturas
heights1=[0 for x in range(n)]
heights2=[0 for x in range(n)]

#Calculando las alturas
DFS_Heigths()

#distancias
distances1=[0 for x in range(n)]
distances2=[0 for x in range(n)]

#Calculando las distancias
DFS_Distances()

#Hallando la mayor distancia de las primeras distancias
min_distance=distances1[numbers_of_attacked_cities[0]]
for i in range(n):
    if important_cities[i] and min_distance>distances1[i]:
        min_distance=distances1[i]

#Hallando el centro
center=[]
for i in range(n):
    if distances1[i]==min_distance:
        center.append(i)

posibles_begin_cities=[]

#Hallando la ciudad por la cual comenzar
for i in center:
    distances_center=BFS(i)
    max_distance=0
    for j in range(n):
        if distances_center[j]>max_distance:
            max_distance=distances_center[j]
    for j in range(n):
        if distances_center[j]==max_distance:
            posibles_begin_cities.append(j)

#Imprimiendo la respuesta
print(min(posibles_begin_cities)+1)
print(2*count_edges-(distances1[center[0]]+distances2[center[0]]))
```


614_B. Gena's Code

It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!

There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.

Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.

Input

The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country.

It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.

Output

Print a single number without leading zeroes — the product of the number of tanks presented by each country.

Examples

Input

3
5 10 1

Output

50

Input

4
1 1 10 11

Output

110

Input

5
0 3 1 100 1

Output

0

Note

In sample 1 numbers 10 and 1 are beautiful, number 5 is not not.

In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.

In sample 3 number 3 is not beautiful, all others are beautiful.

```python
import sys

def esdist(s):
	n=len(s)
	if (s[0] != '1'): return True
	for i in range(1,n):
		if (s[i]!='0'): return True
	return False

l=0
for line in sys.stdin:
	if l==0: n = int(line)
	else: nums = line.split()
	l+=1

res = "1"
ceros = 0
for i in range(n):
	s = nums[i]
	if (not esdist(s)): ceros += len(s)-1
	else:
		res = ""
		if (s[0]=='0'):
			ceros = 1
			break
		res+=s

for i in range(ceros): res+='0';
print (res)

```


662_B. Graph Coloring

You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.

Find the minimum possible number of moves required to make the colors of all edges equal.

Input

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively.

The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci (<image>) providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.

Output

If there is no way to make the colors of all edges equal output  - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move.

If there are multiple optimal sequences of moves, output any of them.

Examples

Input

3 3
1 2 B
3 1 R
3 2 B

Output

1
2

Input

6 5
1 3 R
2 3 R
3 4 B
4 5 R
4 6 R

Output

2
3 4

Input

4 5
1 2 R
1 3 R
2 3 B
3 4 B
1 4 B

Output

-1

```python
from collections import deque

n, m = map(int, input().split())
adj = [[] for i in range(n)]
for i in range(m):
    u, v, c = input().split()
    u, v = int(u)-1, int(v)-1
    adj[u].append((v, c))
    adj[v].append((u, c))

visited = S = T = None

def bfs(i, k):
    q = deque([(i, 0)])
    while q:
        u, p = q.pop()

        if visited[u] >= 0:
            if visited[u] == p: continue
            else: return False

        visited[u] = p
        if p: S.append(u)
        else: T.append(u)

        for v, c in adj[u]:
            nxt = p if c == k else p^1
            q.appendleft((v, nxt))

    return True

def solve(k):
    global visited, S, T
    visited = [-1]*n
    res = []
    for i in range(n):
        if visited[i] < 0:
            S, T = [], []
            if not bfs(i, k):
                return [0]*(n+1)
            else:
                res.extend(S if len(S) < len(T) else T)
    return res

res1 = solve("R")
res2 = solve("B")

if min(len(res1), len(res2)) > n:
    print (-1)
else:
    print (min(len(res1), len(res2)))
    print (" ".join(map(lambda x: str(x+1), res1 if len(res1) < len(res2) else res2)))

```


709_D. Recover the String

For each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x, y}.

In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1 000 000.

Input

The only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109.

Output

If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1 000 000.

Examples

Input

1 2 3 4

Output

Impossible

Input

1 2 2 1

Output

0110

```python
a00, a01, a10, a11 = map(int, input().split())
numZeros = 0
numOnes = 0
ans = True

for n0 in range(1, 2*a00 + 1):
    if n0 * (n0 - 1) == 2 * a00:
        numZeros = n0
        break
    elif n0 * (n0 - 1) > 2 * a00:
        ans = False
        break;

for n1 in range(1, 2*a11 + 1):
    if n1 * (n1 - 1) == 2 * a11:
        numOnes = n1
        break
    elif n1 * (n1 - 1) > 2 * a11:
        ans = False
        break;
res = []

def generateResult(x,a01, a10, n0, n1):
    while n0 > 0 or n1 > 0:
        if a01 >= n1 and n1 > 0:
            if n0 >= 1:
                res.append(0)
                a01 = a01 - n1
                n0 = n0-1
            else:
                return
        elif a10 >= n0 and n0 > 0:
            if n1 >= 1:
                res.append(1)
                a10 = a10 - n0
                n1 = n1-1
            else:
                return
        elif n0 > 0 and n1 > 0:
            return
        elif 0 < n0 == a01 + a10 + n0 + n1:
            for i in range(n0):
                res.append(0)
            n0 = 0
        elif 0 < n1 == a01 + a10 + n0 + n1:
            for i in range(n1):
                res.append(1)
            n1 = 0
        else:
            return

if a01 > 0 or a10 > 0:
    numOnes = max(numOnes, 1)
    numZeros = max(numZeros, 1)

if a00 == a01 == a10 == a11 == 0:
    print(1)
elif a11 == 0 and a00 == 0 and a10 == 1 and a01 == 0:
    print("10")
elif a11 == 0 and a00 == 0 and a01 == 1 and a10 == 0:
    print("01")
elif ans:
    generateResult(res, a01, a10, numZeros, numOnes)
    if len(res) == numZeros + numOnes:
        print("".join(map(str, res)))
    else:
        print("Impossible")
else:
    print("Impossible")

```


754_A. Lesha and array splitting

One spring day on his way to university Lesha found an array A. Lesha likes to split arrays into several parts. This time Lesha decided to split the array A into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays one after another they will form the old array A.

Lesha is tired now so he asked you to split the array. Help Lesha!

Input

The first line contains single integer n (1 ≤ n ≤ 100) — the number of elements in the array A.

The next line contains n integers a1, a2, ..., an ( - 103 ≤ ai ≤ 103) — the elements of the array A.

Output

If it is not possible to split the array A and satisfy all the constraints, print single line containing "NO" (without quotes).

Otherwise in the first line print "YES" (without quotes). In the next line print single integer k — the number of new arrays. In each of the next k lines print two integers li and ri which denote the subarray A[li... ri] of the initial array A being the i-th new array. Integers li, ri should satisfy the following conditions:

  * l1 = 1
  * rk = n
  * ri + 1 = li + 1 for each 1 ≤ i < k.

If there are multiple answers, print any of them.

Examples

Input

3
1 2 -3

Output

YES
2
1 2
3 3

Input

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

Output

YES
2
1 2
3 8

Input

1
0

Output

NO

Input

4
1 2 3 -5

Output

YES
4
1 1
2 2
3 3
4 4

```python
from sys import stdin

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

f = False
for i in range(len(a)):
    if a[i] != 0:
        ln = i
        f = True
        break
if not f:
    print('NO')
else:
    print('YES')
    l = 0
    i = ln + 1
    ans = []
    while i < len(a):
        if a[i] == 0:
            i += 1
        else:
            ans.append((l+1, i))
            l = i
            i += 1
    if l < len(a):
        ans.append((l+1, i))
    print(len(ans))
    for i in ans:
        print(i[0],i[1])

```


774_J. Stepan's Series

Well, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not.

Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch.

Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k.

Input

The first line contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ n) — the number of episodes in the series and the dissatisfaction which should be checked.

The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not.

Output

If Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes).

Examples

Input

5 2
NYNNY

Output

YES

Input

6 1
????NN

Output

NO

Note

In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because k = 2.

In the second test k = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive.

```python
def process(S, k):
    n = len(S)
    if k > n:
        return 'NO'
    current = 0
    for i in range(n):
        if S[i]=='N':
            current+=1
            if current > k:
                return 'NO'
        else:
            current = 0
    start_work = True
    for i in range(k):
        if S[i]=='Y':
            start_work = False
    if start_work and (k==n or k < n and S[k] != 'N'):
        return 'YES'
    if n==1:
        if k==1 and S[0] in ['?N']:
            return 'YES'
        if k==0 and S[0] in ['?Y']:
            return 'YES'
        return 'NO'
    if k==n:
        if 'Y' in S:
            return 'NO'
        return 'YES'
    Y_count = 0
    p1 = 0
    for i in range(1, k+1):
        if S[i]=='Y':
            Y_count+=1
    p2 = i
    for i in range(k+1, n):
       # print(p1, Y_count, p2)
        if Y_count==0 and S[p1] != 'N' and (p2==n-1 or S[p2+1] != 'N'):
            return 'YES'
        p1+=1
        p2+=1
        if p2 < n and S[p2]=='Y':
            Y_count+=1
        if p1 < n and S[p1]=='Y':
            Y_count-=1
  #  print(p1, Y_count, p2)
    if Y_count==0 and p1 < n and S[p1] != 'N':
        return 'YES'
    return 'NO'

n, k = [int(x) for x in input().split()]
S = input()
print(process(S, k))

```


79_C. Beaver

After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly.

However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s.

Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response.

Input

In the first line there is a string s. The length of s will be between 1 and 105, inclusive.

In the second line there is a single integer n (1 ≤ n ≤ 10). Next n lines, there is a string bi (1 ≤ i ≤ n). Each length of bi will be between 1 and 10, inclusive.

Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive.

Output

Output in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s.

If there are several solutions, output any.

Examples

Input

Go_straight_along_this_street
5
str
long
tree
biginteger
ellipse

Output

12 4

Input

IhaveNoIdea
9
I
h
a
v
e
N
o
I
d

Output

0 0

Input

unagioisii
2
ioi
unagi

Output

5 5

Note

In the first sample, the solution is traight_alon.

In the second sample, the solution is an empty string, so the output can be «0 0», «0 1», «0 2», and so on.

In the third sample, the solution is either nagio or oisii.

```python
s, n = input(), int(input())
t = [input() for i in range(n)]

def f(i):
    global t
    for j in range(n):
        if i < j:
            if len(t[j]) < len(t[i]) and t[j] in t[i]: return False
        elif j < i and t[j] in t[i]: return False
    return True

t = [t[i] for i in range(n) if f(i)]
n = len(s)
r = [0] * n

for p in t:
    i, m = -1, len(p) - 1
    while True:
        i = s.find(p, i + 1)
        if i == -1: break
        r[i] += 1
        r[i + m] += 2

d, j, q = 0, -1, [-1]

for i in range(n):
    if r[i] & 1: q.append(i)
    if r[i] & 2:
        j = q.pop(0)
        if i - j > d: d, k = i - j, j

j = q.pop(0)
if n - j > d: d, k = n - j, j

print(d - 1, k + 1)
```


846_A. Curriculum Vitae

Hideo Kojima has just quit his job at Konami. Now he is going to find a new place to work. Despite being such a well-known person, he still needs a CV to apply for a job.

During all his career Hideo has produced n games. Some of them were successful, some were not. Hideo wants to remove several of them (possibly zero) from his CV to make a better impression on employers. As a result there should be no unsuccessful game which comes right after successful one in his CV.

More formally, you are given an array s1, s2, ..., sn of zeros and ones. Zero corresponds to an unsuccessful game, one — to a successful one. Games are given in order they were produced, and Hideo can't swap these values. He should remove some elements from this array in such a way that no zero comes right after one.

Besides that, Hideo still wants to mention as much games in his CV as possible. Help this genius of a man determine the maximum number of games he can leave in his CV.

Input

The first line contains one integer number n (1 ≤ n ≤ 100).

The second line contains n space-separated integer numbers s1, s2, ..., sn (0 ≤ si ≤ 1). 0 corresponds to an unsuccessful game, 1 — to a successful one.

Output

Print one integer — the maximum number of games Hideo can leave in his CV so that no unsuccessful game comes after a successful one.

Examples

Input

4
1 1 0 1

Output

3

Input

6
0 1 0 0 1 0

Output

4

Input

1
0

Output

1

```python
def main():
	n = int(input())
	games = list(map(int, input().split(' ')))

	result = max([games[:i].count(0) + games[i:].count(1) for i in range(n+1)])

	print(result)

if __name__ == "__main__":
	main()

```


867_C. Ordering Pizza

It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.

It is known that the i-th contestant will eat si slices of pizza, and gain ai happiness for each slice of type 1 pizza they eat, and bi happiness for each slice of type 2 pizza they eat. We can order any number of type 1 and type 2 pizzas, but we want to buy the minimum possible number of pizzas for all of the contestants to be able to eat their required number of slices. Given that restriction, what is the maximum possible total happiness that can be achieved?

Input

The first line of input will contain integers N and S (1 ≤ N ≤ 105, 1 ≤ S ≤ 105), the number of contestants and the number of slices per pizza, respectively. N lines follow.

The i-th such line contains integers si, ai, and bi (1 ≤ si ≤ 105, 1 ≤ ai ≤ 105, 1 ≤ bi ≤ 105), the number of slices the i-th contestant will eat, the happiness they will gain from each type 1 slice they eat, and the happiness they will gain from each type 2 slice they eat, respectively.

Output

Print the maximum total happiness that can be achieved.

Examples

Input

3 12
3 5 7
4 6 7
5 9 5

Output

84

Input

6 10
7 4 7
5 8 8
12 5 8
6 11 6
3 3 7
5 9 6

Output

314

Note

In the first example, you only need to buy one pizza. If you buy a type 1 pizza, the total happiness will be 3·5 + 4·6 + 5·9 = 84, and if you buy a type 2 pizza, the total happiness will be 3·7 + 4·7 + 5·5 = 74.

```python
def cns(ts,s):
    if ts/s==int(ts/s):
        return ts
    else:
        return (int(ts/s)+1)*s
n,spp=[int(i) for i in input().split()]
tsr=0
da=[[] for i in range(100005)]
db=[[] for i in range(100005)]
sl=[]
for i in range(n):
    sl.append([int(j) for j in input().split()])
    tsr+=sl[i][0]
    if sl[i][1]>sl[i][2]:
        da[sl[i][1]-sl[i][2]].append(i)
    else:
        db[sl[i][2]-sl[i][1]].append(i)
tsa=cns(tsr,spp)
a1=0
c1=0
for i in range(100000,-1,-1):
    for j in da[i]:
        a1+=sl[j][0]*sl[j][1]
        c1+=sl[j][0]
c1r=cns(c1,spp)-c1
c2r=tsa-cns(c1,spp)
for i in range(100000,-1,-1):
    for j in db[i]:
        if sl[j][0]>c2r:
            a1+=c2r*sl[j][2]
            a1+=(sl[j][0]-c2r)*sl[j][1]
            c2r=0
        else:
            a1+=sl[j][0]*sl[j][2]
            c2r-=sl[j][0]
a2=0
c2=0
for i in range(100000,-1,-1):
    for j in db[i]:
        a2+=sl[j][0]*sl[j][2]
        c2+=sl[j][0]
c2r=cns(c2,spp)-c2
c1r=tsa-cns(c2,spp)
for i in range(100000,-1,-1):
    for j in da[i]:
        if sl[j][0]>c1r:
            a2+=c1r*sl[j][1]
            a2+=(sl[j][0]-c1r)*sl[j][2]
            c1r=0
        else:
            a2+=sl[j][0]*sl[j][1]
            c1r-=sl[j][0]
print(max(a1,a2))

```


914_E. Palindromes in a Tree

You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t.

A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.

For each vertex, output the number of palindromic paths passing through it.

Note: The path from vertex u to vertex v is considered to be the same as the path from vertex v to vertex u, and this path will be counted only once for each of the vertices it passes through.

Input

The first line contains an integer n (2 ≤ n ≤ 2·105) — the number of vertices in the tree.

The next n - 1 lines each contain two integers u and v (1 ≤ u, v ≤ n, u ≠ v) denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree.

The next line contains a string consisting of n lowercase characters from a to t where the i-th (1 ≤ i ≤ n) character is the label of vertex i in the tree.

Output

Print n integers in a single line, the i-th of which is the number of palindromic paths passing through vertex i in the tree.

Examples

Input

5
1 2
2 3
3 4
3 5
abcbb

Output

1 3 4 3 3

Input

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

Output

1 4 1 1 2 4 2

Note

In the first sample case, the following paths are palindromic:

2 - 3 - 4

2 - 3 - 5

4 - 3 - 5

Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic:

1 - 2 - 3

1 - 2 - 3 - 4

1 - 2 - 3 - 5

```python
import sys, os

def centroid_decomp(coupl):
    n = len(coupl)

    bfs = [n - 1]
    for node in bfs:
        bfs += coupl[node]
        for nei in coupl[node]:
            coupl[nei].remove(node)

    size = [0] * n
    for node in reversed(bfs):
        size[node] = 1 + sum(size[child] for child in coupl[node])

    def centroid_reroot(root):
        while coupl[root]:
            child = max(coupl[root], key = size.__getitem__)
            if size[child] <= size[root] // 2:
                break
            size[root] -= size[child]
            size[child] += size[root]
            coupl[root].remove(child)
            coupl[child].append(root)
            root = child
        return root

    bfs = [n - 1]
    for node in bfs:
        centroid = centroid_reroot(node)
        bfs += coupl[centroid]
        yield centroid

inp = sys.stdin.buffer.read().split(); ii = 0

n = int(inp[ii]); ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
    u = int(inp[ii]) - 1; ii += 1
    v = int(inp[ii]) - 1; ii += 1

    coupl[u].append(v)
    coupl[v].append(u)

A = [1 << c - b'a'[0] for c in inp[ii]]; ii += 1
palistates = [0] + [1 << i for i in range(20)]

ans = [0.0] * n
dp = [0.0] * n
val = [0] * n
counter = [0] * (1 << 20)

for centroid in centroid_decomp(coupl):
    bfss = []
    for root in coupl[centroid]:
        bfs = [root]
        for node in bfs:
            bfs += coupl[node]
        bfss.append(bfs)

        for node in bfs:
            val[node] ^= A[node]
            for child in coupl[node]:
                val[child] = val[node]

    entire_bfs = [centroid]
    for bfs in bfss:
        entire_bfs += bfs

    for node in entire_bfs:
        val[node] ^= A[centroid]
        counter[val[node]] += 1

    for bfs in bfss:
        for node in bfs:
            counter[val[node]] -= 1

        for node in bfs:
            v = val[node] ^ A[centroid]
            for p in palistates:
                dp[node] += counter[v ^ p]

        for node in bfs:
            counter[val[node]] += 1

    for node in reversed(entire_bfs):
        dp[node] += sum(dp[child] for child in coupl[node])

    dp[centroid] += 1
    for p in palistates:
        dp[centroid] += counter[p]
    dp[centroid] //= 2

    for node in entire_bfs:
        ans[node] += dp[node]
        counter[val[node]] = val[node] = 0
        dp[node] = 0.0

os.write(1, b' '.join(str(int(x)).encode('ascii') for x in ans))

```


937_C. Save Energy!

Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.

During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.

It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.

Input

The single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).

Output

Print a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9.

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

Examples

Input

3 2 6

Output

6.5

Input

4 2 20

Output

20.0

Note

In the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for <image>. Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for <image>. Thus, after four minutes the chicken will be cooked for <image>. Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready <image>.

In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes.

```python
k,d,t = map(int, input().split())
if k % d == 0:
    print(t)
    exit()
r = k % d
ot = (d-r) /2
ot += k
ct = k + (d-r)

cn = int(t // ot)
ans = cn*ct
rt = t - cn*ot
if rt < k:
    ans += rt
else:
    ans += k
    rt -= k
    ans += rt*2
ans = "%.10f" % float(ans)
print(ans)
```


962_E. Byteland, Berland and Disputed Cities

The cities of Byteland and Berland are located on the axis Ox. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line Ox there are three types of cities:

  * the cities of Byteland,
  * the cities of Berland,
  * disputed cities.

Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.

The countries agreed to connect the pairs of cities with BNET cables in such a way that:

  * If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables,
  * If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables.

Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.

The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.

Each city is a point on the line Ox. It is technically possible to connect the cities a and b with a cable so that the city c (a < c < b) is not connected to this cable, where a, b and c are simultaneously coordinates of the cities a, b and c.

Input

The first line contains a single integer n (2 ≤ n ≤ 2 ⋅ 10^{5}) — the number of cities.

The following n lines contains an integer x_i and the letter c_i (-10^{9} ≤ x_i ≤ 10^{9}) — the coordinate of the city and its type. If the city belongs to Byteland, c_i equals to 'B'. If the city belongs to Berland, c_i equals to «R». If the city is disputed, c_i equals to 'P'.

All cities have distinct coordinates. Guaranteed, that the cities are given in the increasing order of their coordinates.

Output

Print the minimal total length of such set of cables, that if we delete all Berland cities (c_i='R'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables. Similarly, if we delete all Byteland cities (c_i='B'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables.

Examples

Input

4
-5 R
0 P
3 P
7 B

Output

12

Input

5
10 R
14 B
16 B
21 R
32 R

Output

24

Note

In the first example, you should connect the first city with the second, the second with the third, and the third with the fourth. The total length of the cables will be 5 + 3 + 4 = 12.

In the second example there are no disputed cities, so you need to connect all the neighboring cities of Byteland and all the neighboring cities of Berland. The cities of Berland have coordinates 10, 21, 32, so to connect them you need two cables of length 11 and 11. The cities of Byteland have coordinates 14 and 16, so to connect them you need one cable of length 2. Thus, the total length of all cables is 11 + 11 + 2 = 24.

```python
def solve(length, cities):
  result = 0
  lastP = None
  lastB = None
  lastR = None
  maxB = 0
  maxR = 0
  for idx, city in enumerate(cities):
    i, code = city
    if(code == 'B'):
      if(lastB != None):
        result += abs(i - lastB)
        maxB = max(maxB, abs(i - lastB))
      lastB = i
    if(code == 'R'):
      if(lastR != None):
        result += abs(i - lastR)
        maxR = max(maxR, abs(i - lastR))
      lastR = i
    if(code == 'P'):

      # B case
      if(lastB != None):
        result += abs(i - lastB)
        maxB = max(maxB, abs(i - lastB))

      # R case
      if(lastR != None):
        result += abs(i - lastR)
        maxR = max(maxR, abs(i - lastR))

      if(lastP != None):
        result += min(0, abs(i - lastP) - maxB - maxR)
      maxB = 0
      maxR = 0
      lastB = i
      lastR = i
      lastP = i
  return result

if __name__ == '__main__':
  length = int(input())
  cities = []
  for i in range(length):
    data = input().split(" ")
    cities.append((int(data[0]), data[1]))
  result = solve(length, cities)
  print(result)

```


990_A. Commentary Boxes

Berland Football Cup starts really soon! Commentators from all over the world come to the event.

Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.

If n is not divisible by m, it is impossible to distribute the boxes to the delegations at the moment.

Organizers can build a new commentary box paying a burles and demolish a commentary box paying b burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.

What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by m)?

Input

The only line contains four integer numbers n, m, a and b (1 ≤ n, m ≤ 10^{12}, 1 ≤ a, b ≤ 100), where n is the initial number of the commentary boxes, m is the number of delegations to come, a is the fee to build a box and b is the fee to demolish a box.

Output

Output the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by m). It is allowed that the final number of the boxes is equal to 0.

Examples

Input

9 7 3 8

Output

15

Input

2 7 3 7

Output

14

Input

30 6 17 19

Output

0

Note

In the first example organizers can build 5 boxes to make the total of 14 paying 3 burles for the each of them.

In the second example organizers can demolish 2 boxes to make the total of 0 paying 7 burles for the each of them.

In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get 5 boxes.

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

k = n%m
print(min(k*b, (m - k)*a))

```


p02609 AIsing Programming Contest 2020 - Anything Goes to Zero

Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.

Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)

For example, when n=7, it becomes 0 after two operations, as follows:

* \mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.
* \mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.

You are given an integer X with N digits in binary. For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted. Find f(X_1), f(X_2), \ldots, f(X_N).

Constraints

* 1 \leq N \leq 2 \times 10^5
* X is an integer with N digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

N
X

Output

Print N lines. The i-th line should contain the value f(X_i).

Examples

Input

3
011

Output

2
1
1

Input

23
00110111001011011001110

Output

2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3

```python
from sys import stdin
import sys
import itertools
import array
import textwrap
import math

N = int(input())
X = input()
temp = X.count("1")
t = [0, 0, 0]

t[0] = int(X, 2) % (temp-1) if temp != 1 else 0
t[2] = int(X, 2) % (temp+1)
cnt = 0
for i in range(N):
    if X[i] == "1" and temp == 1:
        print(0)
        continue
    if X[i] == "1":
        # p = (1 << (N-i-1)) % (temp-1)
        p = pow(2, N-1-i, temp-1)
        a = (t[0]-p) % (temp-1)
    elif X[i] == "0":
        # m = (1 << (N-i-1)) % (temp+1)
        m = pow(2, N-1-i, temp+1)
        a = (t[2]+m) % (temp+1)
    cnt = 1
    while a > 0:
        a = a % format(a, 'b').count("1")
        cnt += 1
    print(cnt)

```


p02875 AtCoder Grand Contest 040 - Neither AB nor BA

Given is a positive even number N.

Find the number of strings s of length N consisting of `A`, `B`, and `C` that satisfy the following condition:

* s can be converted to the empty string by repeating the following operation:
* Choose two consecutive characters in s and erase them. However, choosing `AB` or `BA` is not allowed.

For example, `ABBC` satisfies the condition for N=4, because we can convert it as follows: `ABBC` → (erase `BB`) → `AC` → (erase `AC`) → `(empty)`.

The answer can be enormous, so compute the count modulo 998244353.

Constraints

* 2 \leq N \leq 10^7
* N is an even number.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings that satisfy the conditions, modulo 998244353.

Examples

Input

2

Output

7

Input

10

Output

50007

Input

1000000

Output

210055358

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

nn = N + 10
P = 998244353

fa = [1] * (nn+1)
fainv = [1] * (nn+1)
for i in range(nn):
    fa[i+1] = fa[i] * (i+1) % P
fainv[-1] = pow(fa[-1], P-2, P)
for i in range(nn)[::-1]:
    fainv[i] = fainv[i+1] * (i+1) % P
C = lambda a, b: fa[a] * fainv[b] % P * fainv[a-b] % P if 0 <= b <= a else 0

ans = pow(3, N, P)
for i in range(N//2 + 1, N + 1):
    ans = (ans - 2 * C(N, i) * pow(2, N - i, P)) % P

print(ans)
```


p03009 diverta 2019 Programming Contest 2 - Balanced Piles

There are N squares arranged in a row, numbered 1 to N from left to right. Takahashi will stack building blocks on these squares, on which there are no blocks yet.

He wants to stack blocks on the squares evenly, so he will repeat the following operation until there are H blocks on every square:

* Let M and m be the maximum and minimum numbers of blocks currently stacked on a square, respectively. Choose a square on which m blocks are stacked (if there are multiple such squares, choose any one of them), and add a positive number of blocks on that square so that there will be at least M and at most M + D blocks on that square.

Tell him how many ways there are to have H blocks on every square by repeating this operation. Since there can be extremely many ways, print the number modulo 10^9+7.

Constraints

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

Input

Input is given from Standard Input in the following format:

N H D

Output

Print the number of ways to have H blocks on every square, modulo 10^9+7.

Examples

Input

2 2 1

Output

6

Input

2 30 15

Output

94182806

Input

31415 9265 3589

Output

312069529

```python
n, h, d = map(int, input().split())
MOD = 10 ** 9 + 7

fact, fact_acc = 1, 1
for i in range(2, n + 1):
    fact = fact * i % MOD
    fact_acc = (fact_acc + fact) % MOD

dp = [0] * (h + 1)
dp[0] = base = fact
for i in range(1, h):
    dp[i] = base * fact_acc % MOD
    base = (base + dp[i]) % MOD
    if i >= d:
        base = (base - dp[i - d]) % MOD
print(base)

```


p03149 KEYENCE Programming Contest 2019 - Beginning

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

* 0 \leq N_1, N_2, N_3, N_4 \leq 9
* N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print `YES`; if they cannot, print `NO`.

Examples

Input

1 7 9 4

Output

YES

Input

1 9 7 4

Output

YES

Input

1 2 9 1

Output

NO

Input

4 9 0 8

Output

NO

```python
n = input().split()
n.sort()
print("YES" if "".join(n) == "1479" else "NO")
```


p03293 AtCoder Beginner Contest 103 - String Rotation

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

* 2 \leq |S| \leq 100
* |S| = |T|
* S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print `Yes`; if it does not, print `No`.

Examples

Input

kyoto
tokyo

Output

Yes

Input

abc
arc

Output

No

Input

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Output

Yes

```python
s=input()*100
t=input()

if t in s:
    print("Yes")
else:
    print("No")

```


p03449 AtCoder Beginner Contest 087 - Candies

We have a 2 \times N grid. We will denote the square at the i-th row and j-th column (1 \leq i \leq 2, 1 \leq j \leq N) as (i, j).

You are initially in the top-left square, (1, 1). You will travel to the bottom-right square, (2, N), by repeatedly moving right or down.

The square (i, j) contains A_{i, j} candies. You will collect all the candies you visit during the travel. The top-left and bottom-right squares also contain candies, and you will also collect them.

At most how many candies can you collect when you choose the best way to travel?

Constraints

* 1 \leq N \leq 100
* 1 \leq A_{i, j} \leq 100 (1 \leq i \leq 2, 1 \leq j \leq N)

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum number of candies that can be collected.

Examples

Input

5
3 2 2 4 1
1 2 2 2 1

Output

14

Input

4
1 1 1 1
1 1 1 1

Output

5

Input

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

Output

29

Input

1
2
3

Output

5

```python
N=int(input())
L1=list(map(int,input().split()))
L2=list(map(int,input().split()))
C=[]
for n in range(N):
  C.append(sum(L1[:n+1])+sum(L2[n:]))
print(max(C))
```


p03609 AtCoder Beginner Contest 072 - Sandglass2

We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand.

How many grams of sand will the upper bulb contains after t seconds?

Constraints

* 1≤X≤10^9
* 1≤t≤10^9
* X and t are integers.

Input

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

X t

Output

Print the number of sand in the upper bulb after t second.

Examples

Input

100 17

Output

83

Input

48 58

Output

0

Input

1000000000 1000000000

Output

0

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

print(X - t if X > t else 0)
```


p03770 AtCoder Grand Contest 012 - Colorful Balls

Snuke arranged N colorful balls in a row. The i-th ball from the left has color c_i and weight w_i.

He can rearrange the balls by performing the following two operations any number of times, in any order:

* Operation 1: Select two balls with the same color. If the total weight of these balls is at most X, swap the positions of these balls.
* Operation 2: Select two balls with different colors. If the total weight of these balls is at most Y, swap the positions of these balls.

How many different sequences of colors of balls can be obtained? Find the count modulo 10^9 + 7.

Constraints

* 1 ≤ N ≤ 2 × 10^5
* 1 ≤ X, Y ≤ 10^9
* 1 ≤ c_i ≤ N
* 1 ≤ w_i ≤ 10^9
* X, Y, c_i, w_i are all integers.

Input

Input is given from Standard Input in the following format:

N X Y
c_1 w_1
:
c_N w_N

Output

Print the answer.

Examples

Input

4 7 3
3 2
4 3
2 1
4 4

Output

2

Input

1 1 1
1 1

Output

1

Input

21 77 68
16 73
16 99
19 66
2 87
2 16
7 17
10 36
10 68
2 38
10 74
13 55
21 21
3 7
12 41
13 88
18 6
2 12
13 87
1 9
2 27
13 15

Output

129729600

```python
class UnionFindVerSize():
    def __init__(self, N):
        self._parent = [n for n in range(0, N)]
        self._size = [1] * N

    def find_root(self, x):
        if self._parent[x] == x: return x
        self._parent[x] = self.find_root(self._parent[x])
        return self._parent[x]

    def unite(self, x, y):
        gx = self.find_root(x)
        gy = self.find_root(y)
        if gx == gy: return

        if self._size[gx] < self._size[gy]:
            self._parent[gx] = gy
            self._size[gy] += self._size[gx]
        else:
            self._parent[gy] = gx
            self._size[gx] += self._size[gy]

    def get_size(self, x):
        return self._size[self.find_root(x)]

    def is_same_group(self, x, y):
        return self.find_root(x) == self.find_root(y)

    def calc_group_num(self):
        N = len(self._parent)
        ans = 0
        for i in range(N):
            if self.find_root(i) == i:
                ans += 1
        return ans

mod = 10**9+7 #出力の制限
N = 2*10**5
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

import sys,bisect

input=sys.stdin.buffer.readline

N,X,Y=map(int,input().split())
cball=[[] for i in range(N)]
ball=[]
color=[-1]*N
for i in range(N):
    c,w=map(int,input().split())
    ball.append((w,c-1,i))
    cball[c-1].append((w,i))
    color[i]=c-1

for i in range(N):
    cball[i].sort()
ball.sort()

if N==1:
    print(1)
    exit()

cmin=[10**20 for i in range(N)]
for i in range(N):
    if cball[i]:
        cmin[i]=min(cball[i][j][0] for j in range(len(cball[i])))

_cmine1=[cmin[i] for i in range(N)]
_cmine2=[cmin[i] for i in range(N)]
for i in range(1,N):
    _cmine1[i]=min(_cmine1[i],_cmine1[i-1])
for i in range(N-2,-1,-1):
    _cmine2[i]=min(_cmine2[i],_cmine2[i+1])
cmine=[0]*N
cmine[0]=_cmine2[1]
cmine[-1]=_cmine1[N-2]
for i in range(1,N-1):
    cmine[i]=min(_cmine1[i-1],_cmine2[i+1])

M=min(ball)
special=-1
for i in range(N):
    if cmine[i]!=M[0]:
        special=i

uf=UnionFindVerSize(N)
for i in range(N):
    if i!=special:
        for j in range(len(cball[i])):
            if M[0]+cball[i][j][0]<=Y:
                uf.unite(cball[i][j][1],M[2])
            if j!=0 and cball[i][j][0]+cball[i][0][0]<=X:
                uf.unite(cball[i][j][1],cball[i][0][1])
    else:
        for j in range(len(cball[special])):
            if cmine[special]+cball[special][j][0]<=Y:
                uf.unite(cball[special][j][1],M[2])
            if M[0]+cball[special][j][0]<=X:
                uf.unite(cball[special][j][1],M[2])

connect={}
for i in range(N):
    root=uf.find_root(i)
    if root not in connect:
        connect[root]=[]
    connect[root].append(i)

ans=1
for root in connect:
    cc={}
    for i in connect[root]:
        if color[i] not in cc:
            cc[color[i]]=0
        cc[color[i]]+=1
    size=len(connect[root])
    for C in cc:
        ans*=g2[cc[C]]
        ans%=mod
    ans*=g1[size]
    ans%=mod

print(ans)
```


p03939 AtCoder Grand Contest 007 - Pushing Balls

There are N balls and N+1 holes in a line. Balls are numbered 1 through N from left to right. Holes are numbered 1 through N+1 from left to right. The i-th ball is located between the i-th hole and (i+1)-th hole. We denote the distance between neighboring items (one ball and one hole) from left to right as d_i (1 \leq i \leq 2 \times N). You are given two parameters d_1 and x. d_i - d_{i-1} is equal to x for all i (2 \leq i \leq 2 \times N).

We want to push all N balls into holes one by one. When a ball rolls over a hole, the ball will drop into the hole if there is no ball in the hole yet. Otherwise, the ball will pass this hole and continue to roll. (In any scenario considered in this problem, balls will never collide.)

In each step, we will choose one of the remaining balls uniformly at random and then choose a direction (either left or right) uniformly at random and push the ball in this direction. Please calculate the expected total distance rolled by all balls during this process.

For example, when N = 3, d_1 = 1, and x = 1, the following is one possible scenario:

c9264131788434ac062635a675a785e3.jpg

* first step: push the ball numbered 2 to its left, it will drop into the hole numbered 2. The distance rolled is 3.
* second step: push the ball numbered 1 to its right, it will pass the hole numbered 2 and drop into the hole numbered 3. The distance rolled is 9.
* third step: push the ball numbered 3 to its right, it will drop into the hole numbered 4. The distance rolled is 6.

So the total distance in this scenario is 18.

Note that in all scenarios every ball will drop into some hole and there will be a hole containing no ball in the end.

Constraints

* 1 \leq N \leq 200,000
* 1 \leq d_1 \leq 100
* 0 \leq x \leq 100
* All input values are integers.

Input

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

N d_1 x

Output

Print a floating number denoting the answer. The relative or absolute error of your answer should not be higher than 10^{-9}.

Examples

Input

1 3 3

Output

4.500000000000000

Input

2 1 0

Output

2.500000000000000

Input

1000 100 100

Output

649620280.957660079002380

```python
def solve(n, d, x):
    ans = 0
    while n:
        ans += d + (2 * n - 1) * x / 2
        d = ((n + 1) * d + 5 * x / 2) / n
        x *= (n + 2) / n
        n -= 1
    return ans

print('{:.10f}'.format(solve(*map(float, input().split()))))

```


p00031 Weight

<image>

My grandmother uses a balance. The balance will balance if you place the same size on both of the two dishes, otherwise it will tilt to the heavier side. The weights of the 10 weights are 1g, 2g, 4g, 8g, 16g, 32g, 64g, 128g, 256g, 512g in order of lightness.

My grandmother says, "Weigh up to about 1 kg in grams." "Then, try to weigh the juice here," and my grandmother put the juice on the left plate and the 8g, 64g, and 128g weights on the right plate to balance. Then he answered, "The total weight is 200g, so the juice is 200g. How is it correct?"

Since the weight of the item to be placed on the left plate is given, create a program that outputs the weight to be placed on the right plate in order of lightness when balancing with the item of the weight given by the balance. However, the weight of the item to be weighed shall be less than or equal to the total weight of all weights (= 1023g).

Hint

The weight of the weight is 2 to the nth power (n = 0, 1, .... 9) g.

Input

Given multiple datasets. For each dataset, the weight of the item to be placed on the left plate is given in one line. Please process until the end of the input. The number of datasets does not exceed 50.

Output

For each data set, separate the weights (ascending order) to be placed on the right plate with one blank and output them on one line.

Example

Input

5
7
127

Output

1 4
1 2 4
1 2 4 8 16 32 64

```python
import sys

l = [2 ** i for i in range(10)]
for line in sys.stdin:
	blist = list(bin(int(line))[2:])
	blist.reverse()
	#print(blist)
	anslist = []
	for i in range(len(blist)):
		if blist[i] == "1":
			anslist.append(str(l[i]))
	print(' '.join(anslist))
```


p00162 Hamming Numbers

The number obtained by multiplying 1 by 2, 3, 5 several times (0 or more times) is called the Hamming numbers. For example

* 1
* 1 x 2 x 2 = 4
* 1 x 2 x 2 x 3 x 5 x 5 = 300

Etc. are humming numbers, but 11, 13, 14 etc. are not humming numbers.

All humming numbers are divisible by a power of 60 (for example, 54 is divisible by 603 = 21600), so they have long been known as convenient numbers for sexagesimal calculations such as time. In just intonation, which is one of the scales used for tuning musical instruments, the ratio of the frequencies of the sounds is a sequence of humming numbers of 24, 27, 30, 32, 36, 40, 45, 48.

Create a program that takes integers m and n as inputs and outputs the number of humming numbers that are m or more and n or less.

Input

A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros.

For each dataset, two integers m and n (1 ≤ m, n ≤ 1000000, m ≤ n) are given on one line, separated by blanks.

The number of datasets does not exceed 20.

Output

Outputs the number of humming numbers from m to n for each data set on one line.

Example

Input

3 8
1 27
1 86
0

Output

5
17
31

```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0162

"""
import sys
from sys import stdin
from bisect import bisect_right, bisect_left
from math import ceil, log
input = stdin.readline

def main(args):
    hammings = []

    temp = set()
    for i in range(ceil(log(1e6, 2)) + 1):
        for j in range(ceil(log(1e6, 3)) + 1):
            for k in range(ceil(log(1e6, 5)) + 1):
                ans = 2**i * 3**j * 5**k
                temp.add(ans)

    hammings = list(temp)
    hammings.sort()

    while True:
        try:
            m, n = map(int, input().split(' '))
        except ValueError:
            break

        s = bisect_left(hammings, m)
        t = bisect_right(hammings, n)

        print(t - s)

if __name__ == '__main__':
    main(sys.argv[1:])

```


p00489 Soccer

problem

Soccer is popular in JOI, and a league match called the JOI League is held every week.

There are N teams in the JOI league, numbered from 1 to N. All combinations of matches are played exactly once. In other words, N × (N -1) / 2 games are played. The outcome of each match is determined by the score of each team. The winning team has 3 points and the losing team has 0 points. In the case of a draw, both teams have one point. The ranking is determined by the total points earned by each team, and the difference in points is not considered. Teams with the same total points will be ranked higher.

As an example, consider a league match with four teams. 4 × (4-1) / 2 = 6 Matches will be played. Suppose those results are as shown in the table below. The left side of the hyphen is the score of the team next to it, and the right side is the score of the team vertically.

Team 1 | Team 2 | Team 3 | Team 4 | Wins | Loss | Draws | Points
--- | --- | --- | --- | --- | --- | --- | --- | ---
Team 1 | --- | 0 --1 | 2 --1 | 2 --2 | 1 | 1 | 1 | 4
Team 2 | 1 --0 | --- | 1 --1 | 3 --0 | 2 | 0 | 1 | 7
Team 3 | 1 --2 | 1 --1 | --- | 1 --3 | 0 | 2 | 1 | 1
Team 4 | 2 --2 | 0 --3 | 3 --1 | --- | 1 | 1 | 1 | 4

At this time, Team 2 with the most points is in first place. The teams with the next most points are Team 1 and Team 4, and both teams are in second place. Team 3 with the fewest points is in 4th place.

Create a program to find the ranking of each team given the results of all matches.

input

The number of teams N (2 ≤ N ≤ 100) is written on the first line of the input file. The following N × (N -1) / 2 lines describe the results of each match. The integers Ai, Bi, Ci, Di (1 ≤ Ai ≤ N, 1 ≤ Bi ≤ N, 0 ≤ Ci ≤ 100, 0) are in the first line (1 ≤ i ≤ N x (N-1) / 2). ≤ Di ≤ 100) is written with a blank as a delimiter, indicating that Team Ai and Team Bi played against each other, and Team Ai scored Ci points and Team Bi scored Di points. Ai ≠ Bi for all i, and the same combination of matches is never written.

output

The output consists of N lines. Each row consists of one integer, and the integer on the i-th row (1 ≤ i ≤ N) represents the rank of team i.

Input / output example

Input example 1

Four
1 2 0 1
1 3 2 1
1 4 2 2
2 3 1 1
2 4 3 0
3 4 1 3

Output example 1

2
1
Four
2

Input / output example 1 corresponds to the example in the problem statement.

Input example 2

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

Output example 2

2
Four
1
Four
3

The results of input / output example 2 are as follows.

| Wins | Loss | Draws | Points
--- | --- | --- | --- | ---
Team 1 | 2 | 1 | 1 | 7
Team 2 | 0 | 1 | 3 | 3
Team 3 | 3 | 0 | 1 | 10
Team 4 | 1 | 3 | 0 | 3
Team 5 | 1 | 2 | 1 | 4

The question text and the data used for the automatic referee are the question text and the test data for scoring, which are created and published by the Japan Committee for Information Olympics.

Example

Input

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

Output

2
1
4
2

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

score = [list(map(lambda x: int(x) - 1 , input().split())) for _ in range(int(n*(n-1)/2))]

points = [0 for _ in range(n)]

for a,b,c,d in score:
    if c > d:
        points[a] += 3
    elif c < d:
        points[b] += 3
    else:
        points[a] += 1
        points[b] += 1

rank = sorted(points)
rank.reverse()

for p in points:
    print(rank.index(p) + 1)
```


p00949 Hidden Anagrams

Example

Input

anagram
grandmother

Output

4

```python
s1 = input()
s2 = input()

cA = ord('a')

s1 = [ord(e) - cA for e in s1]
l1 = len(s1)
s2 = [ord(e) - cA for e in s2]
l2 = len(s2)

ans = 0
for l in range(1, min(l1, l2)+1):
    s = set()
    use = [0]*26

    for i in range(l-1):
        use[s1[i]] += 1
    for i in range(l-1, l1):
        use[s1[i]] += 1
        s.add(tuple(use))
        use[s1[i-l+1]] -= 1

    cnt = [0]*26
    for i in range(l-1):
        cnt[s2[i]] += 1
    for i in range(l-1, l2):
        cnt[s2[i]] += 1
        if tuple(cnt) in s:
            ans = l
            break
        cnt[s2[i-l+1]] -= 1
print(ans)
```


p01352 Graph Construction

There are n rabbits, one in each of the huts numbered 0 through n − 1.

At one point, information came to the rabbits that a secret organization would be constructing an underground passage. The underground passage would allow the rabbits to visit other rabbits' huts. I'm happy.

The passages can go in both directions, and the passages do not intersect. Due to various circumstances, the passage once constructed may be destroyed. The construction and destruction of the passages are carried out one by one, and each construction It is assumed that the rabbit stays in his hut.

Rabbits want to know in advance if one rabbit and one rabbit can play at some stage of construction. Rabbits are good friends, so they are free to go through other rabbit huts when they go out to play. Rabbits who like programming tried to solve a similar problem in the past, thinking that it would be easy, but they couldn't write an efficient program. Solve this problem instead of the rabbit.

Input

The first line of input is given n and k separated by spaces. 2 ≤ n ≤ 40 000, 1 ≤ k ≤ 40 000

In the following k lines, construction information and questions are combined and given in chronological order.

* “1 u v” — A passage connecting huts u and v is constructed. Appears only when there is no passage connecting huts u and v.
* “2 u v” — The passage connecting huts u and v is destroyed. Appears only when there is a passage connecting huts u and v.
* “3 u v” — Determine if the rabbits in the hut u and v can be played.

0 ≤ u <v <n

Output

For each question that appears in the input, output "YES" if you can play, or "NO" if not.

Example

Input

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

Output

YES
NO
YES

```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
    N, K = map(int, readline().split())
    ES = [list(map(int, readline().split())) for i in range(K)]
    emp = {}
    sq = int(K**.5) + 1
    def root(x):
        if x == p[x]:
            return x
        p[x] = y = root(p[x])
        return y
    def unite(x, y):
        px = root(x); py = root(y)
        if px < py:
            p[py] = px
        else:
            p[px] = py
    que = deque()
    used = [0]*N
    lb = 0

    p = [0]*N
    for i in range(sq):
        s = set()
        for j in range(i*sq, min(i*sq+sq, K)):
            t, a, b = ES[j]
            if t == 3:
                continue
            e = (a, b)
            if emp.get(e, 0):
                s.add(e)
            emp[e] = 0

        p[:] = range(N)
        for (v, w), d in emp.items():
            if d == 1:
                unite(v, w)

        G0 = [[] for i in range(N)]
        emp0 = {}
        for a, b in s:
            pa = root(a); pb = root(b)
            if pa == pb:
                continue
            e = (pa, pb) if pa < pb else (pb, pa)
            if e in emp0:
                e1, e2 = emp0[e]
                e1[1] = e2[1] = e1[1] + 1
            else:
                e1 = [pb, 1]; e2 = [pa, 1]
                G0[pa].append(e1)
                G0[pb].append(e2)
                emp0[e] = e1, e2

        for j in range(i*sq, min(i*sq+sq, K)):
            t, a, b = ES[j]
            pa = root(a); pb = root(b)
            e = (pa, pb) if pa < pb else (pb, pa)
            if t == 1:
                emp[a, b] = 1
                if pa == pb:
                    continue
                if e not in emp0:
                    e1 = [pb, 1]; e2 = [pa, 1]
                    G0[pa].append(e1)
                    G0[pb].append(e2)
                    emp0[e] = e1, e2
                else:
                    e1, e2 = emp0[e]
                    e1[1] = e2[1] = e1[1] + 1
            elif t == 2:
                emp[a, b] = 0
                if pa == pb:
                    continue
                e1, e2 = emp0[e]
                e1[1] = e2[1] = e1[1] - 1
            elif t == 3:
                if pa == pb:
                    write("YES\n")
                else:
                    lb += 1
                    que.append(pa)
                    used[pa] = lb
                    while que:
                        v = que.popleft()
                        for w, d in G0[v]:
                            if d and used[w] != lb:
                                used[w] = lb
                                que.append(w)
                    if used[pb] == lb:
                        write("YES\n")
                    else:
                        write("NO\n")
solve()

```


p01534 Anipero 2012

D: Anipero 2012

Anipero Summer Live, commonly known as Anipero, is the largest anime song live event in Japan where various anime song artists gather. 2D, who loves anime songs, decided to go to Anipero this year as well as last year.

He has already purchased m of psyllium to enjoy Anipero. Psyllium is a stick that glows in a chemical reaction when folded. By shaking the psyllium in time with the rhythm, you can liven up the live performance and increase your satisfaction. All the psylliums he purchased this time have the following properties.

* The psyllium becomes darker as time passes after it is folded, and loses its light in 10 minutes.
* Very bright for 5 minutes after folding (hereinafter referred to as "level 2").
* It will be a little dark 5 minutes after folding (hereinafter referred to as "level 1").
* The speed at which light is lost does not change whether it is shaken or not.

2D decided to consider the following problems as to how satisfied he would be with this year's Anipero by properly using the limited psyllium depending on the song.

He anticipates n songs that will be played during the live. The length of each song is 5 minutes. n songs continue to flow, and the interval between songs can be considered as 0 minutes. The following three parameters are given to each song.

* Satisfaction that increases when only one level 2 is shaken for a certain song
* Satisfaction that increases when only one level 1 is shaken for a certain song
* Satisfaction increases when no song is shaken in a certain song

Shaking the glow stick does not necessarily increase satisfaction. If you shake it, it may disturb the atmosphere of the venue and reduce your satisfaction. The same can be said when not shaking.

Psyllium must be used according to the following rules.

* You can fold only when the song starts, and you can fold as many as you like at one time. The time it takes to fold the psyllium can be ignored.
* Up to 8 songs can be played at the same time in one song.
* When shaking multiple psylliums, calculate the satisfaction level to be added by the following formula.
* (Number of Level 1) x (Satisfaction per level 1) + (Number of Level 2) x (Satisfaction per Level 2)
* If no psyllium is shaken, only the satisfaction level when no one is shaken is added.
* Once you decide to shake the psyllium, you cannot change it until the end of one song.
* The psyllium can be left unshaken. Also, it is not necessary to use up all the psyllium.

2D had finished predicting the live song, but he was tired of it and didn't feel like solving the problem. Your job is to write a program for him that seeks the maximum satisfaction you're likely to get at this year's live concert.

Input

Satisfaction information for the expected song list of the live is input.

On the first line, the number of songs n (1 <= n <= 50) sung live and the number m (0 <= m <= 50) of new psyllium that 2D has at the start of the live are separated by spaces. Is entered in. In the following n lines, the information of one song is input line by line. The i-th (1 <= i <= n) song information is

* Satisfaction level when one level 2 psyllium is shaken for song i ai
* Satisfaction level bi when swinging one level 1 psyllium for song i
* Satisfaction ci when no psyllium is shaken in song i

Are entered separated by spaces (-100 <= ai, bi, ci <= 100).

Output

Output the prediction of 2D's maximum satisfaction at the end of the live in one line. Please note that the maximum satisfaction level may be negative. Output a line break at the end of the line.

Sample Input 1

1 5
2 3 8

Sample Output 1

Ten

Sample Input 2

2 10
2 2 20
2 3 -10

Sample Output 2

44

Sample Input 3

3 10
5 1 9
-3 2 1
1 11 0

Sample Output 3

102

Example

Input

1 5
2 3 8

Output

10

```python
INF = 10 ** 20
n, m = map(int, input().split())
dp = [[[-INF] * 9 for _ in range(m + 1)] for _ in range(n + 1)]
dp[0][m][0] = 0
for i in range(n):
  a, b, c = map(int, input().split())
  for rest in range(m + 1):
    for l1 in range(9):
      for l2 in range(min(9, rest + 1)):
        if l1 == 0 and l2 == 0:add = c
        elif l2 == 0:
          if b <= 0:add = max(b, c)
          else:add = max(b * l1, c)
        elif l1 == 0:
          if a <= 0:add = max(a, c)
          else:add = max(a * l2, c)
        else:
          if a <= 0 and b <= 0:add = max(a, b, c)
          elif a <= 0:add = max(b * l1, c)
          elif b <= 0:add = max(a * l2, c)
          elif a <= b:add = max(b * l1 + a * min(l2, 8 - l1), c)
          else:add = max(a * l2 + b * min(l1, 8 - l2), c)
        dp[i + 1][rest - l2][l2] = max(dp[i + 1][rest - l2][l2], dp[i][rest][l1] + add)

ans = -INF
for y in range(m + 1):
  for x in range(9):
    ans = max(ans, dp[n][y][x])
print(ans)

```


p02116 nCm

Problem

Given the integer n, output the smallest m such that nCm (the number of combinations that choose m out of n different ones) is even.

Constraints

The input satisfies the following conditions.

* 1 ≤ n ≤ 1018

Input

The input is given in the following format.

n

Output

Output the minimum m such that nCm is an even number on one line.

Examples

Input

2

Output

1

Input

111

Output

16

Input

3

Output

4


p02256 Greatest Common Divisor

Write a program which finds the greatest common divisor of two natural numbers a and b

Hint

You can use the following observation:

For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y)

Constrants

1 ≤ a, b ≤ 109

Input

a and b are given in a line sparated by a single space.

Output

Output the greatest common divisor of a and b.

Examples

Input

54 20

Output

2

Input

147 105

Output

21

```python
import math
x,y = [int(x) for x in input().split()]
print(math.gcd(x,y))

```


p02404 Print a Frame

Draw a frame which has a height of H cm and a width of W cm. For example, the following figure shows a frame which has a height of 6 cm and a width of 10 cm.

........#
........#
........#
........#

Constraints

* 3 ≤ H ≤ 300
* 3 ≤ W ≤ 300

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the frame made of '#' and '.'.

Print a blank line after each dataset.

Example

Input

3 4
5 6
3 3
0 0

Output

####
#..#
####

######
#....#
#....#
#....#
######

###
#.#
###

```python
while True:
    h, w = [int(i) for i in input().split()]
    if w == h == 0:
        break
    print("#" * w, end="")
    print(("\n#" + "." * (w - 2) + "#") * (h - 2))
    print("#" * w, end="\n\n")

```


1043_C. Smallest Word

IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.

Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" — thought the girl — "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from 1 to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?

A string a is lexicographically smaller than a string b if and only if one of the following holds:

  * a is a prefix of b, but a ≠ b;
  * in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.

Input

The first and the only line contains a string s (1 ≤ |s| ≤ 1000), describing the initial string formed by magnets. The string s consists only of characters 'a' and 'b'.

Output

Output exactly |s| integers. If IA should reverse the i-th prefix (that is, the substring from 1 to i), the i-th integer should be equal to 1, and it should be equal to 0 otherwise.

If there are multiple possible sequences leading to the optimal answer, print any of them.

Examples

Input

bbab

Output

0 1 1 0

Input

aaaaa

Output

1 0 0 0 1

Note

In the first example, IA can reverse the second and the third prefix and get a string "abbb". She cannot get better result, since it is also lexicographically smallest string obtainable by permuting characters of the initial string.

In the second example, she can reverse any subset of prefixes — all letters are 'a'.

```python
s = input()
arr_ans = [0] * len(s)
for i in range(1, len(s)):
    if s[i] == 'a':
        arr_ans[i - 1] = (arr_ans[i - 1] + 1) % 2
        arr_ans[i] += 1
print(*arr_ans)
```