808_B. Average Sleep Time

It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!

When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day.

The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is <image>.

You should write a program which will calculate average sleep times of Polycarp over all weeks.

Input

The first line contains two integer numbers n and k (1 ≤ k ≤ n ≤ 2·105).

The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

Output

Output average sleeping time over all weeks.

The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point.

Examples

Input

3 2
3 4 7

Output

9.0000000000

Input

1 1
10

Output

10.0000000000

Input

8 2
1 2 4 100000 123 456 789 1

Output

28964.2857142857

Note

In the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7.

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

slide = a[:k]
current = sum(slide)
ans = current
for x in range(1,n-k+1):
    current = current - a[x-1] + a[x + k-1]
    ans += current

print("{0:.6f}".format(ans/(n-k+1)))
```


832_C. Strange Radiation

n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed.

You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed.

The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray.

You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106.

Input

The first line contains two integers n and s (2 ≤ n ≤ 105, 2 ≤ s ≤ 106) — the number of people and the rays' speed.

The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≤ vi < s, 1 ≤ ti ≤ 2) — the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively.

It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position.

Output

Print the minimum time needed for both points 0 and 106 to be reached.

Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if <image>.

Examples

Input

2 999
400000 1 2
500000 1 1

Output

500000.000000000000000000000000000000

Input

2 1000
400000 500 1
600000 500 2

Output

400.000000000000000000000000000000

Note

In the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000.

In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106.

```python
import math
leftpeople = set()
rightpeople = set()

n, vl = map(int, input().split())

def leftinterval(x0, v0, t):
    if x0 / v0 <= t:
        return (0, 10**6)
    if x0 / (vl + v0) > t:
        return (-1, -2)
    leftbound = x0
    rightbound = (vl * vl - v0 * v0) * t + x0 * v0
    rightbound /= vl
    rightbound = int(rightbound)
    if rightbound > 10**6:
        rightbound = 10**6
    return (leftbound, rightbound)
def rightinterval(x0, v0, t):
    if (10**6 - x0) / v0 <= t:
        return (0, 10**6)
    if (10**6 - x0) / (v0 + vl) > t:
        return (-1, -2)
    rightbound = x0
    leftbound = v0 * x0 + (10**6) * (vl - v0) - t * (vl * vl - v0 * v0)
    leftbound /= vl
    leftbound = math.ceil(leftbound)
    if(leftbound < 0):
        leftbound = 0
    return (leftbound, rightbound)

def check(t):
    events = []
    for item in leftpeople:
        temp = leftinterval(item[0], item[1], t)
        if(temp[0] > temp[1]):
            continue
        events.append((temp[0], 0, 0))
        events.append((temp[1], 1, 0))
        if(temp[1] - temp[0] == 10**6):
            break
    for item in rightpeople:
        temp = rightinterval(item[0], item[1], t)
        if(temp[0] > temp[1]):
            continue
        events.append((temp[0], 0, 1))
        events.append((temp[1], 1, 1))
        if(temp[1] - temp[0] == 10**6):
            break
    events.sort()
    opened = [0, 0]
    for item in events:
        color = item[2]
        action = item[1]
        if action == 0:
            if opened[(color + 1) % 2] > 0:
                return True
            opened[color] += 1
        else:
            opened[color] -= 1
    return False

for i in range(n):
    a, b, c = map(int, input().split())
    if c == 1:
        leftpeople.add((a, b))
    if c == 2:
        rightpeople.add((a, b))

l = 0
r = 1e9
for i in range(50):
    m = (l + r) / 2
    if(check(m)):
        r = m
    else:
        l = m

print(m)

```


853_A. Planning

Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.

Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.

All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.

Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.

Input

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.

The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.

Output

The first line must contain the minimum possible total cost of delaying the flights.

The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.

Example

Input

5 2
4 2 1 10 2

Output

20
3 6 7 4 5

Note

Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.

However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.

```python
import heapq
n,k = map(int,input().split())
l = list(map(int,input().split()))
ans = [0]*n
h = []
for i in range(k):
    h.append((-1*l[i],i))

heapq.heapify(h)
som = 0
for i in range(k,n+k):
    if i < n:
        heapq.heappush(h, (-1 * l[i], i))

    x = heapq.heappop(h)
    s = -1*x[0]*(i-x[1])
    som += s
    ans[x[1]] = i+1

print(som)
print(*ans)
```


877_E. Danil and a Part-time Job

Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.

Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each room. Danil's duties include switching light in all rooms of the subtree of the vertex. It means that if light is switched on in some room of the subtree, he should switch it off. Otherwise, he should switch it on.

Unfortunately (or fortunately), Danil is very lazy. He knows that his boss is not going to personally check the work. Instead, he will send Danil tasks using Workforces personal messages.

There are two types of tasks:

  1. pow v describes a task to switch lights in the subtree of vertex v.
  2. get v describes a task to count the number of rooms in the subtree of v, in which the light is turned on. Danil should send the answer to his boss using Workforces messages.

A subtree of vertex v is a set of vertices for which the shortest path from them to the root passes through v. In particular, the vertex v is in the subtree of v.

Danil is not going to perform his duties. He asks you to write a program, which answers the boss instead of him.

Input

The first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.

The second line contains n - 1 space-separated integers p2, p3, ..., pn (1 ≤ pi < i), where pi is the ancestor of vertex i.

The third line contains n space-separated integers t1, t2, ..., tn (0 ≤ ti ≤ 1), where ti is 1, if the light is turned on in vertex i and 0 otherwise.

The fourth line contains a single integer q (1 ≤ q ≤ 200 000) — the number of tasks.

The next q lines are get v or pow v (1 ≤ v ≤ n) — the tasks described above.

Output

For each task get v print the number of rooms in the subtree of v, in which the light is turned on.

Example

Input

4
1 1 1
1 0 0 1
9
get 1
get 2
get 3
get 4
pow 1
get 1
get 2
get 3
get 4

Output

2
0
0
1
2
1
1
0

Note

<image> The tree before the task pow 1.

<image> The tree after the task pow 1.

```python
class LazySegTree:
    def __init__(self, init_val, seg_ide, lazy_ide, f, g, h):
        self.n = len(init_val)
        self.num = 2**(self.n-1).bit_length()

        self.seg_ide = seg_ide
        self.lazy_ide = lazy_ide

        self.f = f #(seg, seg) -> seg
        self.g = g #(seg, lazy, size) -> seg
        self.h = h #(lazy, lazy) -> lazy

        self.seg = [seg_ide]*2*self.num
        for i in range(self.n):
            self.seg[i+self.num] = init_val[i]
        for i in range(self.num-1, 0, -1):
            self.seg[i] = self.f(self.seg[2*i], self.seg[2*i+1])

        self.size = [0]*2*self.num
        for i in range(self.n):
            self.size[i+self.num] = 1
        for i in range(self.num-1, 0, -1):
            self.size[i] = self.size[2*i] + self.size[2*i+1]

        self.lazy = [lazy_ide]*2*self.num

    def update(self, i, x):
        i += self.num
        self.seg[i] = x
        while i:
            i = i >> 1
            self.seg[i] = self.f(self.seg[2*i], self.seg[2*i+1])

    def calc(self, i):
        return self.g(self.seg[i], self.lazy[i], self.size[i])

    def calc_above(self, i):
        i = i >> 1
        while i:
            self.seg[i] = self.f(self.calc(2*i), self.calc(2*i+1))
            i = i >> 1

    def propagate(self, i):
        self.seg[i] = self.g(self.seg[i], self.lazy[i], self.size[i])
        self.lazy[2*i] = self.h(self.lazy[2*i], self.lazy[i])
        self.lazy[2*i+1] = self.h(self.lazy[2*i+1], self.lazy[i])
        self.lazy[i] = self.lazy_ide

    def propagate_above(self, i):
        H = i.bit_length()
        for h in range(H, 0, -1):
            self.propagate(i >> h)

    def query(self, l, r):
        l += self.num
        r += self.num
        lm = l // (l & -l)
        rm = r // (r & -r) -1
        self.propagate_above(lm)
        self.propagate_above(rm)

        al = self.seg_ide
        ar = self.seg_ide
        while l < r:
            if l & 1:
                al = self.f(al, self.calc(l))
                l += 1
            if r & 1:
                r -= 1
                ar = self.f(self.calc(r), ar)
            l = l >> 1
            r = r >> 1
        return self.f(al, ar)

    def oprerate_range(self, l, r, a):
        l += self.num
        r += self.num
        lm = l // (l & -l)
        rm = r // (r & -r) -1
        self.propagate_above(lm)
        self.propagate_above(rm)
        while l < r:
            if l & 1:
                self.lazy[l] = self.h(self.lazy[l], a)
                l += 1
            if r & 1:
                r -= 1
                self.lazy[r] = self.h(self.lazy[r], a)
            l = l >> 1
            r = r >> 1

        self.calc_above(lm)
        self.calc_above(rm)

f = lambda x, y: x+y

g = lambda x, a, s: s-x if a%2 == 1 else x

h = lambda a, b: a+b

def EulerTour(g, root):
    n = len(g)
    root = root
    g = g

    tank = [root]
    eulerTour = []
    left = [0]*n
    right = [-1]*n
    depth = [-1]*n
    parent = [-1]*n
    child = [[] for i in range(n)]

    eulerNum = -1
    de = -1

    while tank:
        v = tank.pop()
        if v >= 0:
            eulerNum += 1
            eulerTour.append(v)
            left[v] = eulerNum
            right[v] = eulerNum
            tank.append(~v)
            de += 1
            depth[v] = de
            for u in g[v]:
                if parent[v] == u:
                    continue
                tank.append(u)
                parent[u] = v
                child[v].append(u)
        else:
            de -= 1
            if ~v != root:
                eulerTour.append(parent[~v])
                eulerNum += 1
                right[parent[~v]] = eulerNum
    return eulerTour, left, right

import bisect

import sys
import io, os
input = sys.stdin.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def main():

    n = int(input())
    P = list(map(int, input().split()))
    T = list(map(int, input().split()))

    P = [p-1 for p in P]
    P = [-1]+P

    edge = [[] for i in range(n)]
    for i, p in enumerate(P):
        if p != -1:
            edge[p].append(i)

    et, left, right = EulerTour(edge, 0)
    d = {}
    B = sorted(left)
    #print(B)
    #print(right)
    for i, b in enumerate(B):
        d[b] = i
    A = [0]*n
    for i in range(n):
        A[d[left[i]]] = T[i]

    seg = LazySegTree(A, 0, 0, f, g, h)
    q = int(input())
    for i in range(q):
        query = list(map(str, input().split()))
        if query[0] == 'get':
            u = int(query[1])-1
            l = d[left[u]]
            r = bisect.bisect_right(B, right[u])
            print(seg.query(l, r))
        else:
            u = int(query[1])-1
            l = d[left[u]]
            r = bisect.bisect_right(B, right[u])
            seg.oprerate_range(l, r, 1)

if __name__ == '__main__':
    main()

```


901_A. Hashing Trees

Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.

Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.

Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.

The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.

Input

The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.

The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.

Output

If there is only one tree matching this sequence, print "perfect".

Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.

These treese should be non-isomorphic and should match the given sequence.

Examples

Input

2
1 1 1

Output

perfect

Input

2
1 2 2

Output

ambiguous
0 1 1 3 3
0 1 1 3 2

Note

The only tree in the first example and the two printed trees from the second example are shown on the picture:

<image>

```python
''' Hey stalker :) '''
INF = 10**10
def main():
    print = out.append
    ''' Cook your dish here! '''
    h = get_int()
    li = get_list()
    possible = False
    for i in range(h):
        if li[i]>1 and li[i+1]>1:
            possible = True
            break
    if not possible:
        print("perfect")
        return
    res1 = []
    res2 = []
    for index, i in enumerate(li):
        ele = len(res1)
        for _ in range(i):
            res1.append(ele)
            res2.append(ele)
        if index > 0 and li[index - 1] > 1 and i > 1: res2[-1] -= 1
    print("ambiguous")
    print(" ".join(map(str, res1)))
    print(" ".join(map(str, res2)))
    #print(" ".join(res2))

''' Pythonista fLite 1.1 '''
import sys
#from collections import defaultdict, Counter
#from bisect import bisect_left, bisect_right
#from functools import reduce
#import math
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda: int(input())
get_list = lambda: list(map(int, input().split()))
main()
#[main() for _ in range(int(input()))]
print(*out, sep='\n')

```


923_D. Picking Strings

Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:

  * A <image> BC
  * B <image> AC
  * C <image> AB
  * AAA <image> empty string

Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.

Input

The first line contains a string S (1 ≤ |S| ≤ 105). The second line contains a string T (1 ≤ |T| ≤ 105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.

The third line contains the number of queries Q (1 ≤ Q ≤ 105).

The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?

Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.

It is guaranteed that 1 ≤ a ≤ b ≤ |S| and 1 ≤ c ≤ d ≤ |T|.

Output

Print a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.

Example

Input

AABCCBAAB
ABCB
5
1 3 1 2
2 2 2 4
7 9 1 1
3 4 2 3
4 5 1 3

Output

10011

Note

In the first query we can achieve the result, for instance, by using transitions <image>.

The third query asks for changing AAB to A — but in this case we are not able to get rid of the character 'B'.

```python
def pref_counts(string, char):
    result = [0]
    for c in string:
        result.append(result[-1] + (c == char))
    return result

def left_counts(string, char):
    result = [0]
    for c in string:
        result.append(result[-1] + 1 if c == char else 0)
    return result

s = input().replace("C", "B")
t = input().replace("C", "B")
s_bcounts, t_bcounts = pref_counts(s, "B"), pref_counts(t, "B")
s_lcounts, t_lcounts = left_counts(s, "A"), left_counts(t, "A")
for i in range(int(input())):
    a, b, c, d = list(map(int, input().split()))
    s_b = s_bcounts[b] - s_bcounts[a - 1]
    t_b = t_bcounts[d] - t_bcounts[c - 1]
    s_a = min(s_lcounts[b], b - a + 1)
    t_a = min(t_lcounts[d], d - c + 1)
    answer = False
    if s_b & 1 == t_b & 1:
        if s_b < t_b:
            answer = s_a - (s_b == 0) >= t_a
        elif s_b == t_b:
            answer = s_a >= t_a and (s_a - t_a) % 3 == 0
    print(int(answer), end = "")

```


979_B. Treasure Hunt

After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.

The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.

A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of 7 because its subribbon a appears 7 times, and the ribbon abcdabc has the beauty of 2 because its subribbon abc appears twice.

The rules are simple. The game will have n turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after n turns wins the treasure.

Could you find out who is going to be the winner if they all play optimally?

Input

The first line contains an integer n (0 ≤ n ≤ 10^{9}) — the number of turns.

Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than 10^{5} uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.

Output

Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw".

Examples

Input

3
Kuroo
Shiro
Katie

Output

Kuro

Input

7
treasurehunt
threefriends
hiCodeforces

Output

Shiro

Input

1
abcabc
cbabac
ababca

Output

Katie

Input

15
foPaErcvJ
mZaxowpbt
mkuOlaHRE

Output

Draw

Note

In the first example, after 3 turns, Kuro can change his ribbon into ooooo, which has the beauty of 5, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most 4, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.

In the fourth example, since the length of each of the string is 9 and the number of turn is 15, everyone can change their ribbons in some way to reach the maximal beauty of 9 by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw.

```python
from collections import Counter
n = int(input())
def score(s):
  return Counter(s).most_common()[0][1];
a = [input() for i in range(3)]
l = len(a[0])
a = list(map(score, a))
if n == 1:
  a = list(map(lambda x: x - 1 if x == l else x + 1, a))
else:
  a = list(map(lambda x: min(l, x + n), a))
print('Draw' if a.count(max(a)) > 1 else [['Kuro', 'Shiro', 'Katie'][i] for i in range(3) if a[i] == max(a)][0])

# Made By Mostafa_Khaled
```


999_C. Alphabetic Removals

You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:

  * if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
  * if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
  * ...
  * remove the leftmost occurrence of the letter 'z' and stop the algorithm.

This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.

Help Polycarp find the resulting string.

Input

The first line of input contains two integers n and k (1 ≤ k ≤ n ≤ 4 ⋅ 10^5) — the length of the string and the number of letters Polycarp will remove.

The second line contains the string s consisting of n lowercase Latin letters.

Output

Print the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.

If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).

Examples

Input

15 3
cccaabababaccbc

Output

cccbbabaccbc

Input

15 9
cccaabababaccbc

Output

cccccc

Input

1 1
u

Output

```python
# import collections
import string

letters = list(string.ascii_lowercase)
n, k = map(int, input().split())
a = list(input())

for i in range(n):
    a[i] = (i, a[i])

a.sort(key= lambda x: x[1])
a = a[k:]
a.sort(key= lambda x: x[0])

for i in range(len(a)):
    print(a[i][1], end='')
```


p02665 NOMURA Programming Competition 2020 - Folia

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Constraints

* 0 \leq N \leq 10^5
* 0 \leq A_i \leq 10^{8} (0 \leq i \leq N)
* A_N \geq 1
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Examples

Input

3
0 1 1 2

Output

7

Input

4
0 0 1 0 2

Output

10

Input

2
0 3 1

Output

-1

Input

1
1 1

Output

-1

Input

10
0 0 1 1 2 3 5 8 13 21 34

Output

264

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

a = list(map(int,input().split()))

cumsum_a = a.copy()

for i in range(n-1, -1, -1):
    cumsum_a[i] += cumsum_a[i+1]

ans = 0
node = 1

for i in range(n + 1):
    if a[i] > node:
        ans = -1
        break

    ans += node

    if i < n:
        node = min(2 * (node - a[i]), cumsum_a[i + 1])

print(ans)
```


p02794 AtCoder Beginner Contest 152 - Tree and Constraints

We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i.
Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions?

* The i-th (1 \leq i \leq M) restriction is represented by two integers u_i and v_i, which mean that the path connecting Vertex u_i and Vertex v_i must contain at least one edge painted black.

Constraints

* 2 \leq N \leq 50
* 1 \leq a_i,b_i \leq N
* The graph given in input is a tree.
* 1 \leq M \leq \min(20,\frac{N(N-1)}{2})
* 1 \leq u_i < v_i \leq N
* If i \not= j, either u_i \not=u_j or v_i\not=v_j
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
M
u_1 v_1
:
u_M v_M

Output

Print the number of ways to paint the edges that satisfy all of the M conditions.

Examples

Input

3
1 2
2 3
1
1 3

Output

3

Input

2
1 2
1
1 2

Output

1

Input

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

Output

9

Input

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

Output

62

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

N = int(input())
AB = [list(map(int, input().split())) for _ in range(N - 1)]
M = int(input())
UV = [list(map(int, input().split())) for _ in range(M)]

def popcnt(n):
    c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)
    c = (c & 0x3333333333333333) + ((c >> 2) & 0x3333333333333333)
    c = (c & 0x0f0f0f0f0f0f0f0f) + ((c >> 4) & 0x0f0f0f0f0f0f0f0f)
    c = (c & 0x00ff00ff00ff00ff) + ((c >> 8) & 0x00ff00ff00ff00ff)
    c = (c & 0x0000ffff0000ffff) + ((c >> 16) & 0x0000ffff0000ffff)
    c = (c & 0x00000000ffffffff) + ((c >> 32) & 0x00000000ffffffff)
    return c

graph = [[] for _ in range(N + 1)]
for a, b in AB:
  graph[a].append(b)
  graph[b].append(a)

def make_tree(graph, root) -> (list, list):
  INF = 10 ** 15
  dist = [INF] * len(graph)
  parent = [-1] * len(graph)
  stack = [root]
  dist[root] = 0
  parent[root] = root
  while stack:
    s = stack.pop()
    for g in graph[s]:
      if dist[g] > dist[s] + 1:
        dist[g] = dist[s] + 1
        parent[g] = s
        stack.append(g)
  return dist, parent

def lca(u, v, dist, parent):
  distu, distv = dist[u], dist[v]
  if distu > distv:
    for _ in range(distu - distv):
      u = parent[u]
  if distv > distu:
    for _ in range(distv - distu):
      v = parent[v]
  while u != v:
    u, v = parent[u], parent[v]
  return u

dist, parent = make_tree(graph, 1)

tree_lca = []
for i in range(M):
    tmp = 0
    u, v = UV[i]
    l = lca(u, v, dist, parent)
    while u != l:
        tmp |= 1 << u
        u = parent[u]
    while v != l:
        tmp |= 1 << v
        v = parent[v]
    tree_lca.append(tmp)

answer = 2 ** (N - 1)
for i in range(1, 2 ** M):
    tmp = 0
    for j in range(M):
        if (i >> j) & 1:
            tmp |= tree_lca[j]
    cnt = popcnt(tmp)

    if popcnt(i) % 2 == 1:
        answer -= 2 ** (N - 1 - cnt)
    else:
        answer += 2 ** (N - 1 - cnt)

print(answer)
```


p02930 Japanese Student Championship 2019 Qualification - Classified

AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms.

For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition:

* For each room i\ (1 \leq i \leq N), if we leave Room i, pass through some passages whose levels are all equal and get back to Room i, the number of times we pass through a passage is always even.

Your task is to set levels to the passages so that the highest level of a passage is minimized.

Constraints

* N is an integer between 2 and 500 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print one way to set levels to the passages so that the objective is achieved, as follows:

a_{1,2} a_{1,3} ... a_{1,N}
a_{2,3} ... a_{2,N}
.
.
.
a_{N-1,N}

Here a_{i,j} is the level of the passage connecting Room i and Room j.

If there are multiple solutions, any of them will be accepted.

Example

Input

3

Output

1 2
1

```python
#二部グラフにできるのか
#ここからよ
#実は奇サイクルを含まない=二部グラフとなる
#それぞれのレベルで奇サイクルかどうか
#二部グラフを考えて残りでもどんどん二部グラフを考えるイメージ

#最終的には1or2の状態で残る
N=int(input())
ans=[[0]*N for j in range(N)]
#nはvecの長さ
#次の通路のレベル
def dfs(n,vec,level):
    global ans
    #print(vec)
    #print(n)
    l=vec[:n//2]
    r=vec[n//2:]
    for i in l:
        for j in r:
            ans[i][j]=level
    if len(l)>1:
        dfs(len(l),l,level+1)
    if len(r)>1:
        dfs(len(r),r,level+1)

dfs(N,[i for i in range(N)],1)
for i in range(N-1):
    a=[]
    for j in range(N):
        if i<j:
            a.append(str(ans[i][j]))
    print(" ".join(a))
```


p03066 Tenka1 Programmer Contest 2019 - Banned X

Find the number, modulo 998244353, of sequences of length N consisting of 0, 1 and 2 such that none of their contiguous subsequences totals to X.

Constraints

* 1 \leq N \leq 3000
* 1 \leq X \leq 2N
* N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number, modulo 998244353, of sequences that satisfy the condition.

Examples

Input

3 3

Output

14

Input

8 6

Output

1179

Input

10 1

Output

1024

Input

9 13

Output

18402

Input

314 159

Output

459765451

```python

"""
Writer: SPD_9X2
https://atcoder.jp/contests/tenka1-2019/tasks/tenka1_2019_f
Xが偶数か奇数かは重要な気がする
長さL(<=N)の1,2で構成された文字列の問題、に変換できる
O(L)で求められばおｋ
dpか？

X == 1なら、0,2のみで構成されてればおｋ
X == 2なら、1が2つ以上入っていたら不可能 0 & 1が1つまで
X == 3なら、2を入れる場合→1は入れられないが、2を好きなだけ入れていい
            入れない場合→1を2個まで入れられる
X == 4なら、

→やはり偶奇が重要か？

とどく場合は X-1　→ X+1の移動は強制
すなわち 座標1に行ってはいけない
初手は2に行くしかない
同様にX+2には行けない
X+3に行くしかない
3には行けないから4に行くしかない
つまり2以外不可？？

無限に移動を続ける場合は少なくともX=奇数 2のみ以外無理
偶数の場合はX以前に奇数回1をはさむ必要あり
a→a+1と移動すると、X+a-1から先は移動できなくなる

よって2Xは絶対超えられない
あとは数え上げにどうやって落とすか
Lは固定でいいと思うんだよな
O(L)で解ければ勝ち

dp ?
総和で場合分け or Lで場合分け
総和で場合分けする場合、当然Lは異なるのでまとめる必要がある
Lの長さの移動の寄与にはNCLを掛ける必要がある
移動するときにLは1増えるんだよな…
nC(l+1) = nCl * (n-l)/(l+1)
移動処理を一気に行えばlは統一できるからおｋ？

総和SはX以上の場合 X+1+2kしかありえない
S-X以前は2のみ進軍可能、以降は自由

対称性？
1と2の数を全探索？ ならばO(N**2)でいける
1がA個,2がB個の時、最初と最後に2をいくつか置く必要がある
→後は残りの位置から1を置く場所を選べばよい

→解けたっぽい？

場合分け頑張ろう

合計がX以下の場合→完全に自由
合計が2X以上の場合→Xが奇数の場合のみ all2が可能。それ以外は死
X以上2X以下の場合
→
    S-Xが奇数である必要あり
    まず2を(S-X+1)こ消費する（前後に置く分）
    あとは自由に順列を作ってどうぞ

"""

def modfac(n, MOD):

    f = 1
    factorials = [1]
    for m in range(1, n + 1):
        f *= m
        f %= MOD
        factorials.append(f)
    inv = pow(f, MOD - 2, MOD)
    invs = [1] * (n + 1)
    invs[n] = inv
    for m in range(n, 1, -1):
        inv *= m
        inv %= MOD
        invs[m - 1] = inv
    return factorials, invs

def modnCr(n,r,mod,fac,inv): #上で求めたfacとinvsを引数に入れるべし(上の関数で与えたnが計算できる最大のnになる)

    return fac[n] * inv[n-r] * inv[r] % mod

N,X = map(int,input().split())

mod = 998244353
fac,inv = modfac(N+10,mod)
ans = 0

for two in range(N+1):

    for one in range(N+1):

        if one + two > N:
            break

        dist = one + two*2
        zero = modnCr(N,one+two,mod,fac,inv)
        now = 0

        if dist < X:
            now = modnCr(one+two,one,mod,fac,inv) * zero
        elif dist == X:
            continue
        elif dist < 2*X:
            if (dist-X) % 2 == 0:
                continue
            dtwo = two - (dist-X+1)
            if dtwo >= 0:
                now = modnCr(one+dtwo,one,mod,fac,inv) * zero
        elif X % 2 == 1 and one == 0:
            now = zero

        #print (one,two,now)

        ans += now
        ans %= mod

print (ans)

```


p03209 AtCoder Beginner Contest 115 - Christmas

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

* A level-0 burger is a patty.
* A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like `BPPPB` and `BBPPPBPBPPPBB` (rotated 90 degrees), where `B` and `P` stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

* 1 \leq N \leq 50
* 1 \leq X \leq ( the total number of layers in a level-N burger )
* N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Examples

Input

2 7

Output

4

Input

1 1

Output

0

Input

50 4321098765432109

Output

2160549382716056


p03358 AtCoder Regular Contest 097 - Monochrome Cat

There is a tree with N vertices numbered 1 through N. The i-th edge connects Vertex x_i and y_i. Each vertex is painted white or black. The initial color of Vertex i is represented by a letter c_i. c_i = `W` represents the vertex is white; c_i = `B` represents the vertex is black.

A cat will walk along this tree. More specifically, she performs one of the following in one second repeatedly:

* Choose a vertex that is adjacent to the vertex where she is currently, and move to that vertex. Then, invert the color of the destination vertex.
* Invert the color of the vertex where she is currently.

The cat's objective is to paint all the vertices black. She may start and end performing actions at any vertex. At least how many seconds does it takes for the cat to achieve her objective?

Constraints

* 1 ≤ N ≤ 10^5
* 1 ≤ x_i,y_i ≤ N (1 ≤ i ≤ N-1)
* The given graph is a tree.
* c_i = `W` or c_i = `B`.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_{N-1} y_{N-1}
c_1c_2..c_N

Output

Print the minimum number of seconds required to achieve the objective.

Examples

Input

5
1 2
2 3
2 4
4 5
WBBWW

Output

5

Input

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

Output

7

Input

1
B

Output

0

Input

20
2 19
5 13
6 4
15 6
12 19
13 19
3 11
8 3
3 20
16 13
7 14
3 17
7 8
10 20
11 9
8 18
8 2
10 1
6 13
WBWBWBBWWWBBWWBBBBBW

Output

21

```python

"""

https://atcoder.jp/contests/arc097/tasks/arc097_d

始点と終点関係ある？
→逆にしても問題はない

黒い葉は完全に無視できる(落とせる)
よって、葉はすべて白
葉以外は白黒どっちもあり得る

すべての葉をめぐる最短経路？
ある葉からスタートするのは自明っぽい？
ある白からスタートするのはそう

→自分を塗ってからdfsする
→全方位木dp?

行きのみで帰らない場所が1つ存在するはず
→始点と終点のパスとそこから生える木って感じのイメージ

足踏み(停止)の回数を極力少なくしたい
→始点でも終点でもない場合、 e本の辺がつながってたらe回訪問は確定
　e^colorが黒でない場合は+1
→つまり、各頂点で消費する回数は始点・終点でない限り常に一定？

終点はまず葉→始点も葉でおｋ
始点は足踏みなので1秒つかう　終点も1秒使う
パス上の点は、e-1回訪問(ここが根本的に違う！)

つまり、あるパスがあって　その長さがL(両端除く)の時、最大でL減る
ただし、パス上にあっても回数が減らない点もある

B=0 W=1とするか
(color^E) == 1 の点は、E-1回訪問になると足踏みがいらないから2減る
つまり、そのような点が最大数あるパスを求めればいい

"""

import sys
sys.setrecursionlimit(200000)
from collections import deque

MM = 0

def dfs(v,p):
    global MM

    if v != p and linknum[v] == 1:
        return 0

    cl = []
    for nex in lis[v]:
        if nex != p and exist[nex]:
            tmp = dfs(nex,v)
            cl.append(tmp)
    cl.sort()
    cl.reverse()

    if len(cl) == 1:
        MM = max(MM , cl[0])
    else:
        if (linknum[v]+c[v])%2 == 1:
            MM = max(MM , cl[0] + cl[1] + 2)
        else:
            MM = max(MM , cl[0] + cl[1])

    if (linknum[v]+c[v]) % 2 == 1:
        return cl[0]+ 2
    else:
        return cl[0]

N = int(input())

lis =  [ [] for i in range(N) ]
linknum = [0] * N
for i in range(N-1):
    u,v = map(int,input().split())
    u -= 1
    v -= 1

    lis[u].append(v)
    lis[v].append(u)
    linknum[u] += 1
    linknum[v] += 1

ctmp = input()
c = []

for i in ctmp:
    if i == "B":
        c.append(0)
    else:
        c.append(1)

exist = [True] * N

q = deque([])
for i in range(N):
    if linknum[i] <= 1 and c[i] == 0:
        q.append(i)

while len(q) > 0:
    now = q.popleft()
    exist[now] = False
    linknum[now] = 0

    for nex in lis[now]:
        linknum[nex] -= 1

        if linknum[nex] == 1 and c[nex] == 0:
            q.append(nex)

#print (exist)
start = None
for i in range(N):
    if exist[i]:
        start = i
        break
else:
    print (0)
    sys.exit()

if linknum[start] == 0:
    print (1)
    sys.exit()

ans = 0
#print (linknum)
for i in range(N):
    if exist[i]:

        if (linknum[i] + c[i]) % 2 == 0:
            ans += linknum[i]
        else:
            ans += linknum[i] + 1

MM = 0
pick = dfs(start,start)
print (ans - MM)

```


p03679 AtCoder Beginner Contest 065 - Expired?

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier. He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs `delicious` if he found it delicious, `safe` if he did not found it delicious but did not get a stomachache either, and `dangerous` if he got a stomachache.

Constraints

* 1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print `delicious` if Takahashi found the food delicious; print `safe` if he neither found it delicious nor got a stomachache; print `dangerous` if he got a stomachache.

Examples

Input

4 3 6

Output

safe

Input

6 5 1

Output

delicious

Input

3 7 12

Output

dangerous

```python
x,a,b=map(int,input().split())
print("dangerous" if (a+x)<b else "delicious" if a>=b else "safe")
```


p03834 AtCoder Beginner Contest 051 - Haiku

As a New Year's gift, Dolphin received a string s of length 19.
The string s has the following format: `[five lowercase English letters],[seven lowercase English letters],[five lowercase English letters]`.
Dolphin wants to convert the comma-separated string s into a space-separated string.
Write a program to perform the conversion for him.

Constraints

* The length of s is 19.
* The sixth and fourteenth characters in s are `,`.
* The other characters in s are lowercase English letters.

Input

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

s

Output

Print the string after the conversion.

Examples

Input

happy,newyear,enjoy

Output

happy newyear enjoy

Input

haiku,atcoder,tasks

Output

haiku atcoder tasks

Input

abcde,fghihgf,edcba

Output

abcde fghihgf edcba

```python
a = input()
A = a.replace(","," ")
print(A)
```


p03999 AtCoder Beginner Contest 045 - Many Formulas

You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

* 1 \leq |S| \leq 10
* All letters in S are digits between `1` and `9`, inclusive.

Input

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

S

Output

Print the sum of the evaluated value over all possible formulas.

Examples

Input

125

Output

176

Input

9999999999

Output

12656242944

```python
s = input()
count = 0
for i in range(len(s)):
    for j in range(i + 1, len(s) + 1):
        count += int(s[i:j]) * (2 ** (max(0, (i - 1)) + max(0, (len(s) - j - 1))))
print(count)
```


p00087 Strange Mathematical Expression

Dr .: Peter, I've finally done it.

Peter: See you again? What kind of silly invention is this time?

Dr .: I finally came up with a revolutionary way to process mathematical formulas on a computer. Look at this table.

Ordinary notation | Dr.'s "breakthrough" notation
--- | ---
1 + 2 | 1 2 +
3 * 4 + 7 | 3 4 * 7 +
10 / (2 --12) | 10 2 12-/
(3-4) * (7 + 2 * 3) | 3 4 --7 2 3 * + *

Peter: Yeah.

Dr .: Fufufu. This alone won't tell you what it means to an inexperienced person. It's important from here.

Peter: I mean ...

Dr .: You know that computers have a data structure called a stack. Look, that's "first in, then out".

Peter: Yes. I know, that ...

Dr .: This groundbreaking notation uses that stack. For example, this 10 2 12-/, but process as follows.

Processing target | 10 | 2 | 12 |-| /
--- | --- | --- | --- | --- | ---
| ↓ | ↓ | ↓ | ↓ 2-12 | ↓ 10 / -10
Stack | |.
---
..
Ten
| ..
---
2
Ten
| 12
---
2
Ten
| ..
---
-Ten
Ten
| ..
---
..
-1

Dr .: How is it? You don't have to worry about parentheses or operator precedence, right? The word order is also "10 divided by 2 minus 12", which is somewhat similar to his Far Eastern island nation, Japanese. With this epoch-making invention, our laboratory is safe. Fafafa.

Peter: I mean, Doctor. I learned this in the basic course at the University of Aizu when I was in Japan. Everyone had a simple program called "Reverse Polish Notation".

Dr .: ...

So, instead of Peter, I decided to teach this program to the doctor. Create a program that inputs the formula written in "Reverse Polish Notation" and outputs the calculation result.

input

Given multiple datasets. For each dataset, a formula in Reverse Polish Notation (a string of up to 80 characters with integers and arithmetic symbols separated by one blank character (half-width)) is given on one line. No formula is given that divides a value by 0 or a value that is as close to 0 as possible.

The number of datasets does not exceed 50.

output

Output the calculation result (real number) on one line for each data set. The calculation result may include an error of 0.00001 or less.

Example

Input

10 2 12 - /
3 4 - 7 2 3 * + *
-1 -2 3 + +

Output

-1.000000
-13.000000
0.000000

```python
# Aizu Problem 0087: Strange Mathematical Expression
#
import sys, math, os

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")

def upn(inputs):
    # inverse polish notation
    res = 0
    stack = []
    for inp in inputs:
        if inp in ['+', '-', '*', '/']:
            b = stack.pop()
            a = stack.pop()
            c = str(eval(a + inp + b))
            stack.append(c)
        else:
            stack.append(inp)
    return float(stack[0])

for line in sys.stdin:
    print("%.6f" % upn(line.split()))
```


p00219 A Popular Ice-cream Shop

There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.

For such a store manager, you decided to create a program that displays the number of each ice cream sold in a graph.

Enter the total number of ice creams sold in a day and the number of ice creams sold, and create a program that outputs as many * (half-width asterisks) as the number sold for each type of ice cream. However, the type of ice cream is represented by an integer from 0 to 9. Also, for ice cream with zero sales, one- (half-width hyphen) is output.

Input

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

n
c1
c2
::
cn

The first line gives the total number of ice creams sold per day n (1 ≤ n ≤ 10000). The next n lines are given the i-th ice cream type ci (0 ≤ ci ≤ 9).

The number of datasets does not exceed 20.

Output

For each input dataset, the number of sales is output in numerical order of each ice cream type.

Example

Input

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

Output

*
*
***
*
*
-
*
**
***
**
-
*
-
-
-
*
-
-
-
*

```python
while True:
    c=[0]*10
    n=int(input())
    if n==0:
        break
    for i in range(n):
        a=int(input())
        c[a]+=1
    for i in c:
        if i==0:
            print("-")
        else:
            print("*"*i)

```


p00381 Transporter

In the year 30XX, an expedition team reached a planet and found a warp machine suggesting the existence of a mysterious supercivilization. When you go through one of its entrance gates, you can instantaneously move to the exit irrespective of how far away it is. You can move even to the end of the universe at will with this technology!

The scientist team started examining the machine and successfully identified all the planets on which the entrances to the machine were located. Each of these N planets (identified by an index from $1$ to $N$) has an entrance to, and an exit from the warp machine. Each of the entrances and exits has a letter inscribed on it.

The mechanism of spatial mobility through the warp machine is as follows:

* If you go into an entrance gate labeled with c, then you can exit from any gate with label c.
* If you go into an entrance located on the $i$-th planet, then you can exit from any gate located on the $j$-th planet where $i < j$.

Once you have reached an exit of the warp machine on a planet, you can continue your journey by entering into the warp machine on the same planet. In this way, you can reach a faraway planet. Our human race has decided to dispatch an expedition to the star $N$, starting from Star $1$ and using the warp machine until it reaches Star $N$. To evaluate the possibility of successfully reaching the destination. it is highly desirable for us to know how many different routes are available for the expedition team to track.

Given information regarding the stars, make a program to enumerate the passages from Star $1$ to Star $N$.

Input

The input is given in the following format.

$N$
$s$
$t$

The first line provides the number of the stars on which the warp machine is located $N$ ($2 \leq N \leq 100,000$). The second line provides a string $s$ of length $N$, each component of which represents the letter inscribed on the entrance of the machine on the star. By the same token, the third line provides a string $t$ of length $N$ consisting of the letters inscribed on the exit of the machine. Two strings $s$ and $t$ consist all of lower-case alphabetical letters, and the $i$-th letter of these strings corresponds respectively to the entrance and exit of Star $i$ machine.

Output

Divide the number of possible routes from Star $1$ to Star $N$ obtained above by 1,000,000,007, and output the remainder.

Examples

Input

6
abbaba
baabab

Output

5

Input

25
neihsokcpuziafoytisrevinu
universityofaizupckoshien

Output

4

```python
from collections import defaultdict

MOD = 1000000007
n = int(input())
s = input()
t = input()
dic = defaultdict(int)
dic[s[0]] = 1
for cs, ct in zip(s[1:n-1], t[1:n-1]):
    dic[cs] += dic[ct]
    dic[cs] %= MOD
print(dic[t[-1]])

```


p00597 Finding the Largest Carbon Compound Given Its Long

An bydrocarbon is an organic compound which contains only carbons and hydrogens. An isomer is a compound that has the same number of carbons but different structures. Heptane, for example, is a hydrocarbon with 7 carbons. It has nine isomers. The structural formula of three are shown in Figure 1. Carbons are represented by the letter C, and bonds between carbons are represented by a straight line. In all figures, hydrogens are not represented for simplicity. Each carbon can be connected to a maximum of 4 carbons.

<image>
---
Figure 1: These three examples of isomers of heptane have the same number of carbons but different structures.
---

Let define a chain in an isomer as a sequence of connected carbons without branches. An isomer can have many chains of the same length. Figure 2 shows the longest chain of carbons for each of the represented isomer. Note that there can be many instances of longest chain in an isomer.

<image>
---
Figure 2: The figures shows one instance of longest chain of carbons in each isomer. The first and the second isomers show longest chains of 5 carbons. The longest chain in the third isomer has 4 carbons.
---

Your task is to identify the number of carbons of the largest possible carbon compound whose longest carbon chain has n (1 ≤ n ≤ 30) carbons.

Input

Each input contains a list of number of carbons, i.e. the length of a carbon chain.

The number of input lines is less than or equal to 30.

Output

For each number n in input, identify the number of carbons of the largest possible carbon compound whose longest carbon chain has n carbons.

Example

Input

1
4

Output

1
8

```python
# AOJ 1011: Finding the Largest Carbon Compound Give...
# Python3 2018.7.4 bal4u

a = [0]*32
a[1], a[2] = 1, 2
for i in range(3, 31): a[i] = 3*a[i-2] + 2
while True:
	try: i = int(input())
	except: break
	print(a[i])

```


p00733 Dr. Podboq or: How We Became Asymmetric

After long studying how embryos of organisms become asymmetric during their development, Dr. Podboq, a famous biologist, has reached his new hypothesis. Dr. Podboq is now preparing a poster for the coming academic conference, which shows a tree representing the development process of an embryo through repeated cell divisions starting from one cell. Your job is to write a program that transforms given trees into forms satisfying some conditions so that it is easier for the audience to get the idea.

A tree representing the process of cell divisions has a form described below.

* The starting cell is represented by a circle placed at the top.
* Each cell either terminates the division activity or divides into two cells. Therefore, from each circle representing a cell, there are either no branch downward, or two branches down to its two child cells.

Below is an example of such a tree.

<image>
Figure F-1: A tree representing a process of cell divisions

According to Dr. Podboq's hypothesis, we can determine which cells have stronger or weaker asymmetricity by looking at the structure of this tree representation. First, his hypothesis defines "left-right similarity" of cells as follows:

1. The left-right similarity of a cell that did not divide further is 0.
2. For a cell that did divide further, we collect the partial trees starting from its child or descendant cells, and count how many kinds of structures they have. Then, the left-right similarity of the cell is defined to be the ratio of the number of structures that appear both in the right child side and the left child side. We regard two trees have the same structure if we can make them have exactly the same shape by interchanging two child cells of arbitrary cells.

For example, suppose we have a tree shown below:

<image>
Figure F-2: An example tree

The left-right similarity of the cell A is computed as follows. First, within the descendants of the cell B, which is the left child cell of A, the following three kinds of structures appear. Notice that the rightmost structure appears three times, but when we count the number of structures, we count it only once.

<image>
Figure F-3: Structures appearing within the descendants of the cell B

On the other hand, within the descendants of the cell C, which is the right child cell of A, the following four kinds of structures appear.

<image>
Figure F-4: Structures appearing within the descendants of the cell C

Among them, the first, second, and third ones within the B side are regarded as the same structure as the second, third, and fourth ones within the C side, respectively. Therefore, there are four structures in total, and three among them are common to the left side and the right side, which means the left-right similarity of A is 3/4.

Given the left-right similarity of each cell, Dr. Podboq's hypothesis says we can determine which of the cells X and Y has stronger asymmetricity by the following rules.

1. If X and Y have different left-right similarities, the one with lower left-right similarity has stronger asymmetricity.
2. Otherwise, if neither X nor Y has child cells, they have completely equal asymmetricity.
3. Otherwise, both X and Y must have two child cells. In this case, we compare the child cell of X with stronger (or equal) asymmetricity (than the other child cell of X) and the child cell of Y with stronger (or equal) asymmetricity (than the other child cell of Y), and the one having a child with stronger asymmetricity has stronger asymmetricity.
4. If we still have a tie, we compare the other child cells of X and Y with weaker (or equal) asymmetricity, and the one having a child with stronger asymmetricity has stronger asymmetricity.
5. If we still have a tie again, X and Y have completely equal asymmetricity.

When we compare child cells in some rules above, we recursively apply this rule set.

Now, your job is to write a program that transforms a given tree representing a process of cell divisions, by interchanging two child cells of arbitrary cells, into a tree where the following conditions are satisfied.

1. For every cell X which is the starting cell of the given tree or a left child cell of some parent cell, if X has two child cells, the one at left has stronger (or equal) asymmetricity than the one at right.
2. For every cell X which is a right child cell of some parent cell, if X has two child cells, the one at right has stronger (or equal) asymmetricity than the one at left.

In case two child cells have equal asymmetricity, their order is arbitrary because either order would results in trees of the same shape.

For example, suppose we are given the tree in Figure F-2. First we compare B and C, and because B has lower left-right similarity, which means stronger asymmetricity, we keep B at left and C at right. Next, because B is the left child cell of A, we compare two child cells of B, and the one with stronger asymmetricity is positioned at left. On the other hand, because C is the right child cell of A, we compare two child cells of C, and the one with stronger asymmetricity is positioned at right. We examine the other cells in the same way, and the tree is finally transformed into the tree shown below.

<image>
Figure F-5: The example tree after the transformation

Please be warned that the only operation allowed in the transformation of a tree is to interchange two child cells of some parent cell. For example, you are not allowed to transform the tree in Figure F-2 into the tree below.

<image>
Figure F-6: An example of disallowed transformation

Input

The input consists of n lines (1≤n≤100) describing n trees followed by a line only containing a single zero which represents the end of the input. Each tree includes at least 1 and at most 127 cells. Below is an example of a tree description.

> `((x (x x)) x)`

This description represents the tree shown in Figure F-1. More formally, the description of a tree is in either of the following two formats.

> "`(`" <description of a tree starting at the left child> <single space> <description of a tree starting at the right child> ")"

or

> "`x`"

The former is the description of a tree whose starting cell has two child cells, and the latter is the description of a tree whose starting cell has no child cell.

Output

For each tree given in the input, print a line describing the result of the tree transformation. In the output, trees should be described in the same formats as the input, and the tree descriptions must appear in the same order as the input. Each line should have no extra character other than one tree description.

Sample Input

(((x x) x) ((x x) (x (x x))))
(((x x) (x x)) ((x x) ((x x) (x x))))
(((x x) ((x x) x)) (((x (x x)) x) (x x)))
(((x x) x) ((x x) (((((x x) x) x) x) x)))
(((x x) x) ((x (x x)) (x (x x))))
((((x (x x)) x) (x ((x x) x))) ((x (x x)) (x x)))
((((x x) x) ((x x) (x (x x)))) (((x x) (x x)) ((x x) ((x x) (x x)))))
0

Output for the Sample Input

((x (x x)) ((x x) ((x x) x)))
(((x x) ((x x) (x x))) ((x x) (x x)))
(((x ((x x) x)) (x x)) ((x x) ((x x) x)))
(((x ((x ((x x) x)) x)) (x x)) ((x x) x))
((x (x x)) ((x (x x)) ((x x) x)))
(((x (x x)) (x x)) ((x ((x x) x)) ((x (x x)) x)))
(((x (x x)) ((x x) ((x x) x))) (((x x) (x x)) (((x x) (x x)) (x x))))

Example

Input

(((x x) x) ((x x) (x (x x))))
(((x x) (x x)) ((x x) ((x x) (x x))))
(((x x) ((x x) x)) (((x (x x)) x) (x x)))
(((x x) x) ((x x) (((((x x) x) x) x) x)))
(((x x) x) ((x (x x)) (x (x x))))
((((x (x x)) x) (x ((x x) x))) ((x (x x)) (x x)))
((((x x) x) ((x x) (x (x x)))) (((x x) (x x)) ((x x) ((x x) (x x)))))
0

Output

((x (x x)) ((x x) ((x x) x)))
(((x x) ((x x) (x x))) ((x x) (x x)))
(((x ((x x) x)) (x x)) ((x x) ((x x) x)))
(((x ((x ((x x) x)) x)) (x x)) ((x x) x))
((x (x x)) ((x (x x)) ((x x) x)))
(((x (x x)) (x x)) ((x ((x x) x)) ((x (x x)) x)))
(((x (x x)) ((x x) ((x x) x))) (((x x) (x x)) (((x x) (x x)) (x x))))

```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def parse(S):
    S = S + "$"
    cur = 0
    mp = {"01": 0}
    sp = {"01": {0}}
    sv = {"01": (0, 1)}
    lbl = 1
    fmt = "0{}{}1".format
    def comp(left, right):
        lcs, lb = left
        rcs, rb = right
        a0, b0 = sv[lb]
        a1, b1 = sv[rb]
        if a1*b0 != a0*b1:
            return a1*b0 - a0*b1
        if lcs is None and rcs is None:
            return 0
        ll, lr = lcs
        rl, rr = rcs

        cl = comp(ll, rl)
        if cl != 0:
            return cl
        cr = comp(lr, rr)
        if cr != 0:
            return cr
        return 0
    def expr():
        nonlocal cur, lbl
        if S[cur] == "x":
            cur += 1 # "x"
            return (None, "01")
        cur += 1 # "("
        left = expr()
        cur += 1 # " "
        right = expr()
        cur += 1 # ")"

        lb = left[1]; rb = right[1]

        eb = fmt(lb, rb) if lb < rb else fmt(rb, lb)
        if eb not in mp:
            mp[eb] = lbl
            sp[eb] = sp[lb] | sp[rb] | {lbl}
            sv[eb] = (len(sp[lb] & sp[rb]), len(sp[lb] | sp[rb]))
            lbl += 1
        if comp(left, right) < 0:
            left, right = right, left
        return ((left, right), eb)
    return expr()

def dfs(root, m):
    if root[0] is None:
        return "x"
    left, right = root[0]
    if m == 0:
        return "({} {})".format(dfs(left, 0), dfs(right, 1))
    return "({} {})".format(dfs(right, 0), dfs(left, 1))

def solve():
    S = readline().strip()
    if S == "0":
        return False
    res = parse(S)
    write(dfs(res, 0))
    write("\n")
    return True
while solve():
    ...

```


p01136 Gather the Maps!

It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.

Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, the treasure cannot be found only by a part of the treasure map that points to the location of the treasure. Therefore, all the descendants of Mr. Yao gathered and tried to collect the map in one place. However, even if I tried to put it into practice, I couldn't get together because I couldn't meet the schedule. However, this information about the treasure is valuable information that has been secretly passed down in the clan. Considering the risk of leakage, exchanging maps using public communication means is out of the question.

Therefore, I decided to collect the map for one descendant by repeating the process of meeting the descendants in person and handing over the map. There is no limit to the number of people that one person can meet in a day, but it is necessary that there is a schedule for each other.

Your job is to write a program that asks for at least how many days it will take to collect a map from a list of open days on schedule for each offspring.

By the way, the unity of the Yao clan is very tight. If the descendants who finally get the entire map betray the other descendants and take away the treasure, they will be sanctioned by the clan. The sanctions are so horrifying that it is virtually impossible for their descendants to actually carry away the treasure.

Input

The input consists of multiple datasets.

Each dataset consists of multiple rows. The first line contains the integer n (1 <n <= 50), which represents the number of people with a piece of the map. The next n lines contain the schedule for each descendant. Line i represents the schedule of the i-th descendant, with some integers separated by a single character space. The first integer fi (0 <= fi <= 30) is an integer that represents the number of days that the descendant's schedule is free. The following fi integers represent dates when the schedule is free. These dates differ from each other and are all greater than or equal to 1 and less than or equal to 30.

There is one line containing only 0 at the end of the input.

Output

Print one integer on one line for each dataset. If you can collect the map within 30 days, output the minimum number of days required to collect the map, otherwise output -1.

Addendum: The above "minimum number of days required to collect maps" means the date when all maps are collected earliest starting from one day.

Example

Input

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

Output

3

```python
while True:
  n = int(input())
  if n == 0:
    break
  days = [[] for _ in range(31)]
  for i in range(n):
    hima = list(map(int, input().split()))
    for d in hima[1:]:
      days[d].append(i)

  tos = [{i} for i in range(n)]
  end = {i for i in range(n)}
  for i in range(31):
    gather = set()
    for to in days[i]:
      gather = gather | tos[to]
    if gather == end:
      print(i)
      break
    for to in days[i]:
      tos[to] = gather
  else:
    print(-1)

```


p01275 Dial Lock

A dial lock is a kind of lock which has some dials with printed numbers. It has a special sequence of numbers, namely an unlocking sequence, to be opened.

You are working at a manufacturer of dial locks. Your job is to verify that every manufactured lock is unlocked by its unlocking sequence. In other words, you have to rotate many dials of many many locks.

It’s a very hard and boring task. You want to reduce time to open the locks. It’s a good idea to rotate multiple dials at one time. It is, however, a difficult problem to find steps to open a given lock with the fewest rotations. So you decided to write a program to find such steps for given initial and unlocking sequences.

Your company’s dial locks are composed of vertically stacked k (1 ≤ k ≤ 10) cylindrical dials. Every dial has 10 numbers, from 0 to 9, along the side of the cylindrical shape from the left to the right in sequence. The neighbor on the right of 9 is 0.

A dial points one number at a certain position. If you rotate a dial to the left by i digits, the dial newly points the i-th right number. In contrast, if you rotate a dial to the right by i digits, it points the i-th left number. For example, if you rotate a dial pointing 8 to the left by 3 digits, the dial newly points 1.

You can rotate more than one adjacent dial at one time. For example, consider a lock with 5 dials. You can rotate just the 2nd dial. You can rotate the 3rd, 4th and 5th dials at the same time. But you cannot rotate the 1st and 3rd dials at one time without rotating the 2nd dial. When you rotate multiple dials, you have to rotate them to the same direction by the same digits.

Your program is to calculate the fewest number of rotations to unlock, for given initial and unlocking sequences. Rotating one or more adjacent dials to the same direction by the same digits is counted as one rotation.

Input

The input consists of multiple datasets. Each datset consists of two lines. The first line contains an integer k. The second lines contain two strings, separated by a space, which indicate the initial and unlocking sequences.

The last dataset is followed by a line containing one zero. This line is not a part of any dataset and should not be processed.

Output

For each dataset, print the minimum number of rotations in one line.

Example

Input

4
1357 4680
6
777777 003330
0

Output

1
2

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

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

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    rr = []

    def f(n):
        a,b = LS()
        if a == b:
            return 0
        a = [int(c) for c in a]
        b = [int(c) for c in b]
        aa = [a]
        ad = set()
        ad.add(tuple(a))
        r = 0
        while True:
            r += 1
            na = []
            for a in aa:
                ti = 0
                for i in range(r-1,n):
                    if a[i] != b[i]:
                        ti = i
                        break
                sa = b[ti] - a[ti]
                for j in range(ti+1, n+1):
                    t = [(a[i] + sa) % 10 if ti <= i < j else a[i] for i in range(n)]
                    k = tuple(t)
                    if k in ad:
                        continue
                    if t == b:
                        return r
                    ad.add(k)
                    na.append(t)
            aa = na

    while True:
        n = I()
        if n == 0:
            break
        rr.append(f(n))

    return '\n'.join(map(str,rr))

print(main())

```


p01445 Mobile Network

The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure.

The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every year and is given by a polynomial f(x) of the year x.

Your task is, given the network structure, to write a program to calculate the maximal bandwidth between the 1-st and N-th base stations as a polynomial of x.

Input

The input consists of multiple datasets. Each dataset has the following format:

N M
u1 v1 p1
...
uM vM pM

The first line of each dataset contains two integers N (2 ≤ N ≤ 50) and M (0 ≤ M ≤ 500), which indicates the number of base stations and lines respectively. The following M lines describe the network structure. The i-th of them corresponds to the i-th network line and contains two integers ui and vi and a polynomial pi. ui and vi indicate the indices of base stations (1 ≤ ui, vi ≤ N); pi indicates the network bandwidth.

Each polynomial has the form of:

aLxL + aL-1xL-1 + ... + a2x2 + a1x + a0

where L (0 ≤ L ≤ 50) is the degree and ai's (0 ≤ i ≤ L, 0 ≤ ai ≤ 100) are the coefficients. In the input,

* each term aixi (for i ≥ 2) is represented as <ai>x^<i>
* the linear term (a1x) is represented as <a1>x;
* the constant (a0) is represented just by digits;
* these terms are given in the strictly decreasing order of the degrees and connected by a plus sign ("+");
* just like the standard notations, the <ai> is omitted if ai = 1 for non-constant terms;
* similarly, the entire term is omitted if ai = 0 for any terms; and
* the polynomial representations contain no space or characters other than digits, "x", "^", and "+".

For example, 2x2 + 3x + 5 is represented as 2x^2+3x+5; 2x3 + x is represented as 2x^3+x, not 2x^3+0x^2+1x+0 or the like. No polynomial is a constant zero, i.e. the one with all the coefficients being zero.

The end of input is indicated by a line with two zeros. This line is not part of any dataset.

Output

For each dataset, print the maximal bandwidth as a polynomial of x. The polynomial should be represented in the same way as the input format except that a constant zero is possible and should be represented by "0" (without quotes).

Example

Input

3 3
1 2 x+2
2 3 2x+1
3 1 x+1
2 0
3 2
1 2 x
2 3 2
4 3
1 2 x^3+2x^2+3x+4
2 3 x^2+2x+3
3 4 x+2
0 0

Output

2x+3
0
2
x+2

```python
import collections

class MyList(list):
    def __init__(self, x=[]):
        list.__init__(self, x)

    def __iadd__(self, A):
        ret = MyList()
        for a, b in zip(self, A):
            ret.append(a + b)
        return ret

    def __isub__(self, A):
        ret = MyList()
        for a, b in zip(self, A):
            ret.append(a - b)
        return ret

    def __gt__(self, A):
        for a, b in zip(self, A):
            if a != b:
                return a > b
        return False

class MaxFlow:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
       used in GRL6A(AOJ)
    """
    class Edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V, D):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]
        self.D = D

    def zero(self):
        return MyList([0] * self.D)

    def add_edge(self, fr, to, cap):
        self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
        self.E[to].append(self.Edge(fr, self.zero(), len(self.E[fr])-1))

    def dinic(self, source, sink):
        """find max-flow"""
        INF = MyList([10**9] * self.D)
        maxflow = self.zero()
        while True:
            self.bfs(source)
            if self.level[sink] < 0:
                return maxflow
            self.itr = MyList([0] * self.V)
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > self.zero():
                    maxflow += flow
                else:
                    break

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > self.zero() and self.level[vertex] < self.level[e.to]:
                if flow > e.cap:
                    d = self.dfs(e.to, sink, e.cap)
                else:
                    d = self.dfs(e.to, sink, flow)
                if d > self.zero():
                    e.cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return self.zero()

    def bfs(self, start):
        """find shortest path from start"""
        que = collections.deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0

        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > self.zero() and self.level[e.to] < 0:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)

def to_poly(a, l):
    if l == 0:
        return str(a)
    elif l == 1:
        return "{}x".format('' if a == 1 else a)
    else:
        return "{}x^{}".format('' if a == 1 else a, l)

while True:
    N, M = map(int, input().split())
    if N == M == 0:
        break
    mf = MaxFlow(N, 51)
    for _ in range(M):
        u, v, p = input().split()
        u, v = int(u)-1, int(v)-1
        poly = MyList([0] * 51)
        for x in p.split('+'):
            try:
                num = int(x)
                poly[-1] = num
            except ValueError:
                a, l = x.split('x')
                if l:
                    poly[-int(l.strip("^"))-1] = int(a) if a else 1
                else:
                    poly[-2] = int(a) if a else 1
        mf.add_edge(u, v, poly)
        mf.add_edge(v, u, poly)
    maxflow = mf.dinic(0, N-1)
    ans = '+'.join(to_poly(a, l) for a, l in zip(maxflow, reversed(range(51))) if a)
    print(ans if ans else 0)
```


p01751 Yamanote Line

Mr. A wants to get to the destination on the Yamanote line.

After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also, Mr. A will continue to take the same train even if he overtakes it, and the train will take 60 minutes to go around the Yamanote line. Therefore, Mr. A will arrive at the destination after 60t + c (t is a non-negative integer) minutes.

How many minutes will A be able to reach his destination? Output -1 when it is unreachable. However, if the time you arrive at your destination is the boundary between the time you are sleeping and the time you are awake, you can get off.

Constraints

* 0 <a, b, c <60

Input

The input is given in one line in the following format.

a b c

The input consists of three integers a, b, c.

a is the time you are awake, b is the time you are sleeping, and c is the time it takes to get to your destination after boarding. The unit of a, b, and c is minutes.

Output

If you can reach your destination, output the time it takes to reach your destination. Otherwise, output -1.

Examples

Input

10 10 5

Output

5

Input

50 40 51

Output

111

Input

20 20 20

Output

20

Input

30 30 40

Output

-1

```python
"山手線"
a, b, c = map(int, input().split())

flag = True
if a+b == 60 and c > a:  # 必ず辿りつけない
    print(-1)
else:
    right = 0
    left = a
    i = 0
    while True:
        # print('left : ', left)
        # print('right : ', right)
        # print('c : ', c)
        if left >= c and c >= right:
            print(c)
            break
        if left+b > c and c > right+a:
            c += 60
        left += (b+a)
        right += (a+b)
        i += 1
        if i > 60:
            print(-1)
            break

```


p01891 Cabbage

Problem statement

AOR Ika got a cabbage with $ N $ leaves. The leaves of this cabbage are numbered $ 1, \ ldots, N $ in order from the outside, and the dirtiness of the $ i $ th leaf is $ D_i $. The larger this value is, the worse the degree of dirt is. AOR Ika-chan decided to use the cabbage leaves for cooking, so she decided to select the dirty leaves to be discarded according to the following procedure.

1. Initialize the discard candidates to empty.
2. Focus on the outermost leaves that have not yet been examined. If all the items have been checked, the process ends.
3. If the leaf is dirty for $ A $ or more, add it to the discard candidate and return to 2. Otherwise it ends.

However, as a result of this operation, I noticed that the number of leaves that can be used for cooking may be extremely reduced. Therefore, I decided to reconsider the leaves to be discarded after the above operation and perform the following operations.

1. If there are less than $ M $ leaves that are not candidates for disposal, proceed to 2. Otherwise it ends.
2. Focus on the innermost leaf that has not been examined yet among the leaves that are candidates for disposal. If there are no leaves that are candidates for disposal, the process ends.
3. If the leaf is less than $ B $, remove it from the discard candidates and return to 2. Otherwise, discard all the leaves remaining in the discard candidates and finish.

When you perform these operations, find the number of leaves to be finally discarded.

Input constraints

$ 1 \ leq N \ leq 1000 $
$ 0 \ leq M \ leq N $
$ 1 \ leq A \ leq B \ leq 1000 $
$ 1 \ leq D_ {i} \ leq 1000 $

sample

Sample input 1

5 3 6 9
9 7 5 3 1

Sample output 1

2

Discard the first and second sheets.

Sample input 2

5 3 6 9
5 4 3 2 1

Sample output 2

0

Do not throw away from the first piece.

Sample input 3

5 3 6 9
10 8 6 4 2

Sample output 3

1

I tried to throw away the third one, but I reconsidered and decided not to throw away the second and third ones.

Sample input 4

5 3 6 9
5 10 8 6 4

Sample output 4

0

AOR Ika doesn't know that the second piece is dirty.

Sample input 5

5 0 6 9
9 9 8 8 7

Sample output 5

Five

I don't mind throwing everything away.

input

$ N \ M \ A \ B $
$ D_ {1} \ D_ {2} \ \ cdots \ D_ {N} $

output

Output the number of leaves to be finally thrown away.

Example

Input

5 3 6 9
9 7 5 3 1

Output

2

```python
#!/usr/bin/env python3

def solve(n, m, a, b, ds):
    is_waste = [False for _ in range(n)]
    for i in range(n):
        if ds[i] >= a:
            is_waste[i] = True
        else:
            break
    if sum(is_waste) > n - m:
        for i in range(n)[::-1]:
            if is_waste[i]:
                if ds[i] <= b:
                    is_waste[i] = False
                else:
                    break
    return sum(is_waste)

def main():
    n, m, a, b = map(int, input().split())
    ds = list(map(int, input().split()))
    print(solve(n, m, a, b, ds))

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


p02028 Mail Order

N: Mail order

Mr. Komozawa bought building blocks toys from Makai mail order.

The building blocks are in the shape of a cube with a side length of 1, and are stacked on squares divided into $ H $ pieces vertically and $ W $ pieces horizontally.

Seen from the side, $ A_1, A_2, A_3, \ dots, A_H $ blocks were stacked in order from the left.

When viewed from the front, $ B_1, B_2, B_3, \ dots, B_W $ blocks were stacked in order from the left.

Mr. Komozawa is great, so I decided to guess the total number of blocks from this information alone.

If you answer a small number and make a mistake, it will be awkward, so I would like to answer the maximum number that can be considered.

input

The first line is given the integers $ H, W $, separated by blanks.

On the second line, $ H $ integers $ A_1, A_2, A_3, \ dots, A_H $ representing the figure when viewed from the side are given, separated by blanks.

On the third line, $ W $ integers $ B_1, B_2, B_3, \ dots, B_W $ representing the front view are given, separated by blanks.

output

Output the maximum number of blocks that can be considered from this information.

Constraint

* $ H, W $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 \ 000 $
* $ A_1, A_2, A_3, \ dots, A_H $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 \ 000 \ 000 $
* $ B_1, B_2, B_3, \ dots, B_W $ are integers greater than or equal to $ 1 $ and less than or equal to $ 100 \ 000 \ 000 $
* It is guaranteed that there is a stacking method of blocks that meets the conditions for all inputs.

Input example 1

twenty two
1 5
1 5

Output example 1

8

Let's represent the $ X $ th cell in the vertical direction and the $ Y $ th cell in the horizontal direction by $ (X, Y) $.

A total of $ 8 $ if 5 pieces are stacked on the mass $ (2, 2) $ and $ 1 $ is stacked on the mass $ (1, 1) $, $ (1, 2) $, $ (2, 1) $. Blocks will be piled up.

The answer is $ 8 $, as it is unlikely that you have more than $ 9 $.

Input example 2

3 3
2 4 5
3 1 5

Output example 2

twenty two

Example

Input

2 2
1 5
1 5

Output

8

```python
from bisect import bisect_left as bl
from itertools import accumulate

h, w= map(int, input().split())
aList = sorted(map(int, input().split()))
bList = list(map(int, input().split()))
acc = [0]+list(accumulate(aList))
aList.insert(0, -1)

ans = 0
for b in bList:
    index = bl(aList, b)
    ans += acc[index - 1] + (h - index + 1) * b
print(ans)

```


p02170 Coin and Die

Problem

There are coins with front and back sides and dice with rolls from $ 1 $ to $ N $. Gacho decided to play the following games using these.

The game starts with a score of $ 0 $ and proceeds as follows.

1. Roll the dice $ 1 $ and add the number of rolls to the score.
2. If the current score is $ K $ or more, the game is cleared and the game ends.
3. If the current score is less than $ K $, toss a coin and return to 1. if the front appears, and if the back appears, the game is over and the game ends.

When a coin is thrown, it has a probability of $ A \% $ and a probability of $ (100-A) \% $. Also, when the dice are rolled, each eye appears with equal probability.
At this time, find the probability that Gacho can clear the game in one game.
When the probability to be calculated is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $ $ 0 $ or more and $ 998244352 $ or less. Output the integer $ R $ of. Under the constraints of this problem, such $ R $ always exists uniquely.

Constraints

The input satisfies the following conditions.

* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \ leq K \ leq 10 ^ 5 $
* $ 1 \ leq A \ leq 99 $
* All inputs are integers

Input

The input is given in the following format.

$ N $ $ K $ $ A $

$ N, K, A $ are given on one line separated by blanks.

Output

When the probability of clearing the game is expressed as $ \ frac {P} {Q} $ using relatively prime integers $ P and Q $, it becomes $ R \ times Q \ equiv P \ bmod 998244353 $. Output an integer $ R $ that is greater than or equal to $ 0 $ and less than or equal to $ 998244352 $.

Examples

Input

1 1 50

Output

1

Input

2 2 10

Output

648858830

Input

6 10 99

Output

650893870

```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 998244353

def solve():
    n,k,a = LI()
    lst = [0]*(k+1)
    lst[-2] = 1
    A = a*pow(100*n,mod-2,mod)
    inv = pow(n,mod-2,mod)

    for i in range(k-1)[::-1]:
        if k > i + n:
            lst[i] = A*(lst[i+1] - lst[i+n+1]) + lst[i+1]
            lst[i] %= mod
        else:
            lst[i] = A*(lst[i+1] - lst[k]) + (n-(k-i)+1)*inv + lst[i+1]
            lst[i] %= mod
    print((lst[0] - lst[1])%mod)
    return

if __name__ == "__main__":
    solve()

```


p02311 Common Tangent

Find common tangent lines of two circles $c1$ and $c2$.

Constraints

* $-1,000 \leq c1x, c1y, c2x, c2y \leq 1,000$
* $1 \leq c1r, c2r \leq 1,000$
* $c1$ and $c2$ are different

Input

Center coordinates ($cix$, $ciy$) and radii $cir$ of two circles $c1$ are $c2$ are given in the following format.

$c1x \; c1y \; c1r$
$c2x \; c2y \; c2r$

All input values are given in integers.

Output

Print coordinates of the tangent points on circle $c1$ based on the following rules.

* Print the coordinate with smaller $x$ first. In case of a tie, print the coordinate with smaller $y$ first.

The output values should be in a decimal fraction with an error less than 0.00001.

Examples

Input

1 1 1
6 2 2

Output

0.6153846154 1.9230769231
1.0000000000 0.0000000000
1.4183420913 1.9082895434
1.7355040625 0.3224796874

Input

1 2 1
4 2 2

Output

0.6666666667 1.0571909584
0.6666666667 2.9428090416
2.0000000000 2.0000000000

Input

1 2 1
3 2 2

Output

0.5000000000 1.1339745962
0.5000000000 2.8660254038

Input

0 0 1
1 0 2

Output

-1.0000000000 0.0000000000

Input

0 0 1
0 0 2

Output

```python
from math import acos, atan2, cos, hypot, isclose, pi, sin
from typing import List, Tuple

def tangent_points(c1x: float, c1y: float, c1r: float,
                   c2x: float, c2y: float, c2r: float) -> List[Tuple[float, float]]:
    c1c2 = hypot(c2x - c1x, c2y - c1y)
    t0 = atan2(c2y - c1y, c2x - c1x)
    ps: List[Tuple[float, float]] = []

    r1r2 = c1r + c2r
    if isclose(c1c2, r1r2):
        ps.append((c1x + c1r * cos(t0), c1y + c1r * sin(t0)))
    elif c1c2 > r1r2:
        t1 = acos(r1r2 / c1c2)
        ps.append((c1x + c1r * cos(t0 + t1), c1y + c1r * sin(t0 + t1)))
        ps.append((c1x + c1r * cos(t0 - t1), c1y + c1r * sin(t0 - t1)))

    r1r2 = c1r - c2r
    if isclose(c1c2, abs(r1r2)):
        if r1r2 > 0.0:
            t1 = 0.0
        else:
            t1 = pi
        ps.append((c1x + c1r * cos(t0 + t1), c1y + c1r * sin(t0 + t1)))
    elif c1c2 > abs(r1r2):
        if r1r2 > 0.0:
            t1 = acos(r1r2 / c1c2)
        else:
            t1 = pi - acos(-r1r2 / c1c2)
        ps.append((c1x + c1r * cos(t0 + t1), c1y + c1r * sin(t0 + t1)))
        ps.append((c1x + c1r * cos(t0 - t1), c1y + c1r * sin(t0 - t1)))

    return ps

if __name__ == "__main__":
    c1x, c1y, c1r = map(lambda x: float(x), input().split())
    c2x, c2y, c2r = map(lambda x: float(x), input().split())

    ps = tangent_points(c1x, c1y, c1r, c2x, c2y, c2r)

    for p in sorted(ps):
        print("{:.6f} {:.6f}".format(*p))

```


p02459 Map: Search

For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.

* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the corresponding value with $x$.
* get($key$): Print the value with the specified $key$.

Constraints

* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consits of lower-case letter
* For a get operation, the element with the specified key exists in $M$.

Input

The input is given in the following format.

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

Each query $query_i$ is given by

0 $key$ $x$

or

1 $key$

where the first digits 0, 1 and 2 represent insert and get operations respectively.

Output

For each get operation, print an integer in a line.

Example

Input

7
0 blue 4
0 red 1
0 white 5
1 red
1 blue
0 black 8
1 black

Output

1
4
8

```python
from collections import defaultdict

def main():
    q = int(input())
    d = defaultdict(int)

    for _ in range(q):
        para = input().split()

        if para[0] == "0":
            d[para[1]] = int(para[2])

        elif para[0] == "1":
            print(d[para[1]])
main()

```


1005_F. Berland and the Shortest Paths

There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.

It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.

The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:

  * it is possible to travel from the capital to any other city along the n-1 chosen roads,
  * if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).

In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).

The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.

Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.

Input

The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.

The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.

Output

Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.

In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.

Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.

If there are several answers, output any of them.

Examples

Input

4 4 3
1 2
2 3
1 4
4 3

Output

2
1110
1011

Input

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

Output

1
101001

Input

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

Output

2
111100
110110

```python
import sys
import io, os
input = sys.stdin.buffer.readline

n,m,k = map(int,input().split())
AB = []
g = [[] for _ in range(n)]
for i in range(m):
    a,b = map(int, input().split())
    a,b = a-1, b-1
    g[a].append(b)
    g[b].append(a)
    AB.append((a,b))
from collections import deque
q = deque([])
q.append(0)
d = [-1]*n
d[0] = 0
while q:
    v = q.popleft()
    for u in g[v]:
        if d[u] == -1:
            d[u] = d[v]+1
            q.append(u)
#print(d)
inc = [[] for _ in range(n)]
for i, (a, b) in enumerate(AB):
    if d[a]+1 == d[b]:
        inc[b].append(i)
    if d[b]+1 == d[a]:
        inc[a].append(i)
#print(inc)

F = [0]*n
res = []
for i in range(k):
    s = ['0']*m
    for j in range(1, n):
        s[inc[j][F[j]]] = '1'
    res.append(''.join(s))
    flag = False
    for j in range(1, n):
        if F[j]+1 < len(inc[j]):
            flag = True
            F[j] += 1
            break
        else:
            F[j] = 0
    if not flag:
        break
print(len(res))
print(*res, sep='\n')

```


1029_E. Tree with Small Distances

You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.

Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.

Input

The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.

The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.

Output

Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.

Examples

Input

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

Output

2

Input

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

Output

0

Input

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

Output

1

Note

The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].

The tree corresponding to the second example: <image> The answer is 0.

The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).

```python
from sys import stdin
n = int(stdin.readline())
g = dict()
for i in range(n-1):
    u,v = map(int,stdin.readline().split())
    g.setdefault(u-1,[]).append(v-1)
    g.setdefault(v-1, []).append(u-1)
st = [0]
rank = [0]*n
tree = [0]*n
msk = [0]*n
rd = dict()
while len(st)>0:
    top = st.pop()
    msk[top] = 1
    for c in g[top]:
        if msk[c] == 0:
            st.append(c)
            tree[c] = top
            rank[c] = rank[top]+1
            rd.setdefault(rank[c], []).append(c)
max_rank = max(rank)
reach = [0]*n
build = [0]*n
ans = 0
for r in range(max_rank, 2, -1):
    for node in rd[r]:
        if reach[node] == 0:
            reach[node] = 1
            reach[tree[node]] = 1
            reach[tree[tree[node]]] = 1
            build[tree[node]] = 1
print(sum(build))
```