630_D. Hexagons!

After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.

Some of magic effects are able to affect several field cells at once, cells that are situated not farther than n cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.

It is easy to see that the number of cells affected by a magic effect grows rapidly when n increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given n, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than n cells away from a given cell.

<image>

Input

The only line of the input contains one integer n (0 ≤ n ≤ 109).

Output

Output one integer — the number of hexagons situated not farther than n cells away from a given cell.

Examples

Input

2

Output

19


658_A. Bear and Reverse Radewoosh

Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.

There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it's guaranteed that pi < pi + 1 and ti < ti + 1.

A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0, pi - c·x) points.

Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by pi). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by pi). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.

You may assume that the duration of the competition is greater or equal than the sum of all ti. That means both Limak and Radewoosh will accept all n problems.

Input

The first line contains two integers n and c (1 ≤ n ≤ 50, 1 ≤ c ≤ 1000) — the number of problems and the constant representing the speed of loosing points.

The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 1000, pi < pi + 1) — initial scores.

The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 1000, ti < ti + 1) where ti denotes the number of minutes one needs to solve the i-th problem.

Output

Print "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points.

Examples

Input

3 2
50 85 250
10 15 25

Output

Limak

Input

3 6
50 85 250
10 15 25

Output

Radewoosh

Input

8 1
10 20 30 40 50 60 70 80
8 10 58 63 71 72 75 76

Output

Tie

Note

In the first sample, there are 3 problems. Limak solves them as follows:

  1. Limak spends 10 minutes on the 1-st problem and he gets 50 - c·10 = 50 - 2·10 = 30 points.
  2. Limak spends 15 minutes on the 2-nd problem so he submits it 10 + 15 = 25 minutes after the start of the contest. For the 2-nd problem he gets 85 - 2·25 = 35 points.
  3. He spends 25 minutes on the 3-rd problem so he submits it 10 + 15 + 25 = 50 minutes after the start. For this problem he gets 250 - 2·50 = 150 points.

So, Limak got 30 + 35 + 150 = 215 points.

Radewoosh solves problem in the reversed order:

  1. Radewoosh solves 3-rd problem after 25 minutes so he gets 250 - 2·25 = 200 points.
  2. He spends 15 minutes on the 2-nd problem so he submits it 25 + 15 = 40 minutes after the start. He gets 85 - 2·40 = 5 points for this problem.
  3. He spends 10 minutes on the 1-st problem so he submits it 25 + 15 + 10 = 50 minutes after the start. He gets max(0, 50 - 2·50) = max(0, - 50) = 0 points.

Radewoosh got 200 + 5 + 0 = 205 points in total. Limak has 215 points so Limak wins.

In the second sample, Limak will get 0 points for each problem and Radewoosh will first solve the hardest problem and he will get 250 - 6·25 = 100 points for that. Radewoosh will get 0 points for other two problems but he is the winner anyway.

In the third sample, Limak will get 2 points for the 1-st problem and 2 points for the 2-nd problem. Radewoosh will get 4 points for the 8-th problem. They won't get points for other problems and thus there is a tie because 2 + 2 = 4.

```python
n,c = map(int,input().split())
p=input().split()
t=input().split()
sl=0
sr=0
ti=0
for i in range(n):
    ti+=int(t[i])
    if int(p[i])-c*ti>=0:
        sl+=int(p[i])-c*ti
ti=0
for i in range(n):
    ti+=int(t[n-i-1])
    if int(p[n-i-1])-c*ti>=0:
        sr+=int(p[n-i-1])-c*ti
if sl == sr:
    print('Tie')
elif sl>sr:
    print('Limak')
else:
    print('Radewoosh')

```


680_C. Bear and Prime 100

This is an interactive problem. In the output section below you will see the information about flushing the output.

Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.

Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.

You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".

For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.

When you are done asking queries, print "prime" or "composite" and terminate your program.

You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.

You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).

Input

After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.

Output

Up to 20 times you can ask a query — print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input.

In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program.

To flush you can use (just after printing an integer and end-of-line):

  * fflush(stdout) in C++;
  * System.out.flush() in Java;
  * stdout.flush() in Python;
  * flush(output) in Pascal;
  * See the documentation for other languages.

Hacking. To hack someone, as the input you should print the hidden number — one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.

Examples

Input

yes
no
yes

Output

2
80
5
composite

Input

no
yes
no
no
no

Output

58
59
78
78
2
prime

Note

The hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.

<image>

The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.

<image>

59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).

```python
# from __future__ import division, print_function

import sys
import os
from io import BytesIO, IOBase

# def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input

# n = int(os.read(0,100))
# if(n==1):
#     os.write(1,b'! 1')
#     sys.stdout.flush()
# else:
#     per = [0]*n
#     # print('? 2 1')
#     # sys.stdout.flush()
#     a1 = query(1,0)
#     # print('? 1 2')
#     # sys.stdout.flush()
#     a2 = int(query(0,1))
#     if(a2>a1):
#         max = 2
#         per[0] = a2
#     else:
#         max = 1
#         per[1] = a1
#     # print(per)
#     for i in range(3,n+1):
#         # print('? '+str(i)+" "+str(max))
#         # sys.stdout.flush()
#         a1 = int(query(i-1,max-1))
#         # print('? '+str(max)+' '+str(i))
#         # sys.stdout.flush()
#         a2  = int(query(max-1,i-1))
#         if(a1>a2):
#             per[i-1] = a1
#         else:
#             per[max-1] = a2
#             max = i
#         # print(per)
#     per[max-1] = n
#     # print('! ',end="")
#     # print(' '.join(str(per[i]) for i in range(len(per))))
#     # sys.stdout.flush()
#     os.write(1, b'! ')
#     os.write(1, b' '.join(str(x).encode('ascii') for x in per))

def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def query(a):
    # print(1)
    os.write(1,b"%d\n" % a)
    return str(os.read(0,100))

def solve(case):
    cnt = 0
    primes = [2,3,5,7]
    div = []
    for i in range(len(primes)):
        # print(primes[i])
        # sys.stdout.flush()
        # ans = inp()
        ans = query(primes[i])
        # print(ans)
        if('yes' in ans):
            div.append(primes[i])
            cnt+=1

    if(cnt == 0):
        print('prime')
    else:
        if(len(div) == 1):
            i = div[0]
            x = 2
            cnt = 0
            while((i**x)<101):
                # print(i**x)
                # sys.stdout.flush()
                if('yes' in query(i**x)):
                    cnt+=1
                    break
                x+=1
            new = []
            for i in range(10,50):
                if(isPrime(i)):
                    new.append(i)
            for i in new:
                if(div[0]*i>100):
                    break
                # print(i)
                # sys.stdout.flush()
                if('yes' in query(i)):
                    cnt+=1
            if(cnt == 0):
                print('prime')
            else:
                print('composite')
        else:
            print('composite')

solve(1)

```


703_B. Mishka and trip

Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.

Here are some interesting facts about XXX:

  1. XXX consists of n cities, k of whose (just imagine!) are capital cities.
  2. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci.
  3. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1 — 2 — ... — n — 1. Formally, for every 1 ≤ i < n there is a road between i-th and i + 1-th city, and another one between 1-st and n-th city.
  4. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1 ≤ i ≤ n, i ≠ x, there is a road between cities x and i.
  5. There is at most one road between any two cities.
  6. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ci·cj.

Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (a < b), such that there is a road between a and b you are to find sum of products ca·cb. Will you help her?

Input

The first line of the input contains two integers n and k (3 ≤ n ≤ 100 000, 1 ≤ k ≤ n) — the number of cities in XXX and the number of capital cities among them.

The second line of the input contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10 000) — beauty values of the cities.

The third line of the input contains k distinct integers id1, id2, ..., idk (1 ≤ idi ≤ n) — indices of capital cities. Indices are given in ascending order.

Output

Print the only integer — summary price of passing each of the roads in XXX.

Examples

Input

4 1
2 3 1 2
3

Output

17

Input

5 2
3 5 2 2 4
1 4

Output

71

Note

This image describes first sample case:

<image>

It is easy to see that summary price is equal to 17.

This image describes second sample case:

<image>

It is easy to see that summary price is equal to 71.

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

def main():
    n, k = rints()
    a, b = rints(), set(rints())
    su, ans, su2 = sum(a), 0, 0

    for i in b:
        ans += a[i - 1] * (su - a[i - 1])
        su2 += a[i - 1]

    for i in range(n):
        if i + 1 not in b:
            x, y = (i - 1) % n, (i + 1) % n
            ans += a[i] * (su2 + a[x] * (x + 1 not in b) + a[y] * (y + 1 not in b))

    print(ans >> 1)

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

BUFSIZE = 8192
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
rstr = lambda: input().strip()
rstrs = lambda: [str(x) for x in input().split()]
rstr_2d = lambda n: [rstr() for _ in range(n)]
rint = lambda: int(input())
rints = lambda: [int(x) for x in input().split()]
rint_2d = lambda n: [rint() for _ in range(n)]
rints_2d = lambda n: [rints() for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b

if __name__ == '__main__':
    main()

```


725_B. Food on the Plane

A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle.

<image>

It's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row 1 while the second attendant serves row 3. When both rows are done they move one row forward: the first attendant serves row 2 while the second attendant serves row 4. Then they move three rows forward and the first attendant serves row 5 while the second attendant serves row 7. Then they move one row forward again and so on.

Flight attendants work with the same speed: it takes exactly 1 second to serve one passenger and 1 second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one — in seat 'c'. Assume that all seats are occupied.

Vasya has seat s in row n and wants to know how many seconds will pass before he gets his lunch.

Input

The only line of input contains a description of Vasya's seat in the format ns, where n (1 ≤ n ≤ 1018) is the index of the row and s is the seat in this row, denoted as letter from 'a' to 'f'. The index of the row and the seat are not separated by a space.

Output

Print one integer — the number of seconds Vasya has to wait until he gets his lunch.

Examples

Input

1f

Output

1

Input

2d

Output

10

Input

4a

Output

11

Input

5e

Output

18

Note

In the first sample, the first flight attendant serves Vasya first, so Vasya gets his lunch after 1 second.

In the second sample, the flight attendants will spend 6 seconds to serve everyone in the rows 1 and 3, then they will move one row forward in 1 second. As they first serve seats located to the right of the aisle in order from window to aisle, Vasya has to wait 3 more seconds. The total is 6 + 1 + 3 = 10.


747_B. Mammoth's Genome Decoding

The process of mammoth's genome decoding in Berland comes to its end!

One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.

It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.

Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.

Input

The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome.

The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.

Output

If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).

Examples

Input

8
AG?C??CT

Output

AGACGTCT

Input

4
AGCT

Output

AGCT

Input

6
????G?

Output

===

Input

4
AA??

Output

===

Note

In the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.

In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.

In the third and the fourth examples it is impossible to decode the genom.

```python
n, s, g, c, r = int(input()), input(), 'ACGT', [], '==='
if n % 4 != 0:
    exit(print(r))
for i in g:
    c.append(s.count(i))
    if c[-1] > n // 4:
        exit(print(r))
for i in range(4):
    for j in range(c[i], n // 4):
        s = s.replace('?', g[i], 1)
print(s)

```


76_E. Points

You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.

Input

The first line of input contains one integer number N (1 ≤ N ≤ 100 000) — the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≤ X, Y ≤ 10 000) — the coordinates of points. Two or more points may coincide.

Output

The only line of output should contain the required sum of squares of distances between all pairs of points.

Examples

Input

4
1 1
-1 -1
1 -1
-1 1

Output

32

```python
import math

if __name__== '__main__':
    n = int(input())
    n_1= n- 1
    totalDistance= 0
    Xs= []
    Ys= []
    xs= []
    ys= []
    xAddition= 0
    yAddition= 0

    for _ in range(n):
        x, y= [int(x) for x in input().split()]
        Xs.append(n_1* x* x)
        Ys.append(n_1* y* y)
        xs.append(x)
        ys.append(y)
        xAddition+= x
        yAddition+= y

    for index in range(n):
        xAddition-= xs[index]
        subtract= 2* xs[index]* xAddition
        totalDistance+= Xs[index]- subtract

        yAddition-= ys[index]
        subtract= 2* ys[index]* yAddition
        totalDistance+= Ys[index]- subtract
    print(totalDistance)

```


794_B. Cutting Carrot

Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area.

Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area?

<image> Illustration to the first example.

Input

The first and only line of input contains two space-separated integers, n and h (2 ≤ n ≤ 1000, 1 ≤ h ≤ 105).

Output

The output should contain n - 1 real numbers x1, x2, ..., xn - 1. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0 < x1 < x2 < ... < xn - 1 < h must hold.

Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10 - 6.

Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if <image>.

Examples

Input

3 2

Output

1.154700538379 1.632993161855

Input

2 100000

Output

70710.678118654752

Note

Definition of isosceles triangle: <https://en.wikipedia.org/wiki/Isosceles_triangle>.

```python
from math import sqrt

n,hn = list(map(int,input().split()))
kn = sqrt(n)
h = hn/kn
for i in range(1,n):
    print(h*sqrt(i),end = ' ')
```


815_A. Karen and Game

On the way to school, Karen became fixated on the puzzle game on her phone!

<image>

The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.

One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.

To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.

Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!

Input

The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively.

The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500).

Output

If there is an error and it is actually not possible to beat the level, output a single integer -1.

Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level.

The next k lines should each contain one of the following, describing the moves in the order they must be done:

  * row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row".
  * col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column".

If there are multiple optimal solutions, output any one of them.

Examples

Input

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

Output

4
row 1
row 1
col 4
row 3

Input

3 3
0 0 0
0 1 0
0 0 0

Output

-1

Input

3 3
1 1 1
1 1 1
1 1 1

Output

3
row 1
row 2
row 3

Note

In the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:

<image>

In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.

In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:

<image>

Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.

```python
from itertools import product

n, m = map(int, input().split())
matr = []
for i in range(n):
    matr.append([int(num) for num in input().split()])

def walker(start_row, start_col, dif_row, dif_col):
    row = start_row
    col = start_col
    while 0 <= row < n and 0 <= col < m:
        yield row, col
        row += dif_row
        col += dif_col

def walker_row(row):
    return walker(row, 0, 0, 1)

def walker_col(col):
    return walker(0, col, 1, 0)

def get_min(line):
    res = float('inf')
    for row, col in line:
        res = min(res, matr[row][col])
    return res

def subtract(line, diff):
    for row, col in line:
        matr[row][col] -= diff

def resolve_rows():
    for row in range(n):
        min_num = get_min(walker_row(row))
        if min_num > 0:
            subtract(walker_row(row), min_num)
            step = 'row {}'.format(row + 1)
            for i in range(min_num):
                ans.append(step)

def resolve_cols():
    for col in range(m):
        min_num = get_min(walker_col(col))
        if min_num > 0:
            subtract(walker_col(col), min_num)
            step = 'col {}'.format(col + 1)
            for i in range(min_num):
                ans.append(step)

ans = []
if n > m:
    resolve_cols()
    resolve_rows()
else:
    resolve_rows()
    resolve_cols()

cant = False
for row, col in product(range(n), range(m)):
    cant |= matr[row][col] > 0

if cant:
    print(-1)
else:
    print(len(ans))
    print('\n'.join(ans))

```


840_A. Leha and Function

Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.

But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 ≤ i, j ≤ m the condition Ai ≥ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.

Input

First line of input data contains single integer m (1 ≤ m ≤ 2·105) — length of arrays A and B.

Next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 109) — array A.

Next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109) — array B.

Output

Output m integers a'1, a'2, ..., a'm — array A' which is permutation of the array A.

Examples

Input

5
7 3 5 3 4
2 1 3 2 3

Output

4 7 3 5 3

Input

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

Output

2 6 4 5 8 8 6

```python
import operator
class pa():
	def __init__(self,b,i):
		self.b = b
		self.i = i

n = int(input())

a = list(map(int,input().strip().split(' ')))
b = list(map(int,input().strip().split(' ')))

a.sort()
m = []
for i in range(n):
	tp = pa(b[i],i)
	m.append(tp)

m.sort(key=operator.attrgetter('b'))
c = [0]*n

for i in range(n):
	c[m[i].i] = a[n-i-1]

out =  ''
for i in range(n):
	out += str(c[i]) + ' '
print(out)
```


860_B. Polycarp's phone book

There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.

There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then:

  * if he enters 00 two numbers will show up: 100000000 and 100123456,
  * if he enters 123 two numbers will show up 123456789 and 100123456,
  * if he enters 01 there will be only one number 100123456.

For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.

Input

The first line contains single integer n (1 ≤ n ≤ 70000) — the total number of phone contacts in Polycarp's contacts.

The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.

Output

Print exactly n lines: the i-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the i-th number from the contacts. If there are several such sequences, print any of them.

Examples

Input

3
123456789
100000000
100123456

Output

9
000
01

Input

4
123456789
193456789
134567819
934567891

Output

2
193
81
91

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

s, p = {}, [''] * n

for k in range(n):

    p[k] = t = input()

    for q in [t[i: j] for i in range(9) for j in range(i + 1, 10)]:

        s[q] = -1 if q in s and s[q] != k else k

for q, k in s.items():

    if k >= 0 and len(p[k]) > len(q): p[k] = q

print('\n'.join(p))

# Made By Mostafa_Khaled
```


887_A. Div. 64

Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.

Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.

Input

In the only line given a non-empty binary string s with length up to 100.

Output

Print «yes» (without quotes) if it's possible to remove digits required way and «no» otherwise.

Examples

Input

100010001

Output

yes

Input

100

Output

no

Note

In the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.

You can read more about binary numeral system representation here: <https://en.wikipedia.org/wiki/Binary_system>

```python
n=list(input())
m=len(n)
e=0
s=1
if n.count('1')==0:
    s=0
for i in range(0,m):
    if n[i]=='1':
        e=i
        break
k=n[e:]
if s==1:
    if k.count('0')>=6:
        print('yes')
    else:
        print('no')
else:
    print('no')

```


90_A. Cableway

A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.

A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.

The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.

All students are divided into three groups: r of them like to ascend only in the red cablecars, g of them prefer only the green ones and b of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,

The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.

Input

The first line contains three integers r, g and b (0 ≤ r, g, b ≤ 100). It is guaranteed that r + g + b > 0, it means that the group consists of at least one student.

Output

Print a single number — the minimal time the students need for the whole group to ascend to the top of the mountain.

Examples

Input

1 3 2

Output

34

Input

3 2 1

Output

33

Note

Let's analyze the first sample.

At the moment of time 0 a red cablecar comes and one student from the r group get on it and ascends to the top at the moment of time 30.

At the moment of time 1 a green cablecar arrives and two students from the g group get on it; they get to the top at the moment of time 31.

At the moment of time 2 comes the blue cablecar and two students from the b group get on it. They ascend to the top at the moment of time 32.

At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.

At the moment of time 4 a green cablecar arrives and one student from the g group gets on it. He ascends to top at the moment of time 34.

Thus, all the students are on the top, overall the ascension took exactly 34 minutes.


931_D. Peculiar apple-tree

In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.

Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.

Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.

Input

First line of input contains single integer number n (2 ≤ n ≤ 100 000) — number of inflorescences.

Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.

Output

Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.

Examples

Input

3
1 1

Output

1

Input

5
1 2 2 2

Output

3

Input

18
1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4

Output

4

Note

In first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.

In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it.

```python
from collections import Counter

tree = []

class Node:
    def __init__(self, num=None):
        self.length = 0 if num is None else tree[num-1].length + 1

def main():
    n = int(input())
    global tree
    tree = [Node()]

    for x in input().split():
        tree.append(Node(int(x)))

    print(sum([value & 1 for key, value in Counter([x.length for x in tree]).items()]))

if __name__ == "__main__":
    main()

```


958_F2. Lightsabers (medium)

There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.

Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k1 knights with lightsabers of the first color, k2 knights with lightsabers of the second color, ..., km knights with lightsabers of the m-th color.

However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights.

Input

The first line of the input contains n (1 ≤ n ≤ 2·105) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k1, k2, ..., km (with <image>) – the desired counts of Jedi Knights with lightsabers of each color from 1 to m.

Output

Output one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output  - 1.

Example

Input

8 3
3 3 1 2 2 1 1 3
3 1 1

Output

1

```python
n, m = map(int, input().split())
c = list(map(int, input().split()))
k = list(map(int, input().split()))
p = [0] * m
c = [i -1 for i in c]
s = sum(k)
cnt = k.count(0)
l = 0
r = 0
while r < n and cnt < m:
    p[c[r]] += 1
    if p[c[r]] == k[c[r]]:
        cnt += 1
    r += 1
if cnt != m:
    print(-1)
    exit(0)
ans = r-l
while l < n:
    p[c[l]] -= 1
    while r < n and p[c[l]] < k[c[l]]:
        p[c[r]] += 1
        r += 1
    if p[c[l]] >= k[c[l]]:
        ans = min(ans, r-l-1)
    elif r == n:
        break
    l += 1
print(ans-s)

```


985_D. Sand Fortress

You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right.

Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height hi of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it.

Finally you ended up with the following conditions to building the castle:

  * h1 ≤ H: no sand from the leftmost spot should go over the fence;
  * For any <image> |hi - hi + 1| ≤ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen;
  * <image>: you want to spend all the sand you brought with you.

As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible.

Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.

Input

The only line contains two integer numbers n and H (1 ≤ n, H ≤ 1018) — the number of sand packs you have and the height of the fence, respectively.

Output

Print the minimum number of spots you can occupy so the all the castle building conditions hold.

Examples

Input

5 2

Output

3

Input

6 8

Output

3

Note

Here are the heights of some valid castles:

  * n = 5, H = 2, [2, 2, 1, 0, ...], [2, 1, 1, 1, 0, ...], [1, 0, 1, 2, 1, 0, ...]
  * n = 6, H = 8, [3, 2, 1, 0, ...], [2, 2, 1, 1, 0, ...], [0, 1, 0, 1, 2, 1, 1, 0...] (this one has 5 spots occupied)

The first list for both cases is the optimal answer, 3 spots are occupied in them.

And here are some invalid ones:

  * n = 5, H = 2, [3, 2, 0, ...], [2, 3, 0, ...], [1, 0, 2, 2, ...]
  * n = 6, H = 8, [2, 2, 2, 0, ...], [6, 0, ...], [1, 4, 1, 0...], [2, 2, 1, 0, ...]


p02577 AtCoder Beginner Contest 176 - Multiple of 9

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

* 0 \leq N < 10^{200000}
* N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print `Yes`; otherwise, print `No`.

Examples

Input

123456789

Output

Yes

Input

0

Output

Yes

Input

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Output

No

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

if n % 9 is 0:
	print('Yes')
else:
	print('No')
```


p02708 AtCoder Beginner Contest 163 - Sum of Large Numbers

We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N.

We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7).

Constraints

* 1 \leq N \leq 2\times 10^5
* 1 \leq K \leq N+1
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of possible values of the sum, modulo (10^9+7).

Examples

Input

3 2

Output

10

Input

200000 200001

Output

1

Input

141421 35623

Output

220280457

```python
n,k=map(int,input().split())
mod=10**9+7
ans=0
for i in range(k,n+2):
    ans=(ans+(n-i+1)*i+1)%mod
print(ans)
```


p02837 AtCoder Beginner Contest 147 - HonestOrUnkind2

There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.

Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.

How many honest persons can be among those N people at most?

Constraints

* All values in input are integers.
* 1 \leq N \leq 15
* 0 \leq A_i \leq N - 1
* 1 \leq x_{ij} \leq N
* x_{ij} \neq i
* x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)
* y_{ij} = 0, 1

Input

Input is given from Standard Input in the following format:

N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

Output

Print the maximum possible number of honest persons among the N people.

Examples

Input

3
1
2 1
1
1 1
1
2 0

Output

2

Input

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

Output

0

Input

2
1
2 0
1
1 0

Output

1

```python
n = int(input())
evi = []
for _ in range(n):
    m = int(input())
    evi.append([list(map(int, input().split())) for _ in range(m)])
ans = 0
for i in range(1 << n):
    for j in range(n):
        if ((i >> j) & 1) == 1:
            for x,y in evi[j]:
                if ((i >> (x-1))&1) != y:
                    break
            else:
                continue
            break
    else:
        ans = max(ans,bin(i).count('1'))
print(ans)
```


p02974 AtCoder Beginner Contest 134 - Permutation Oddness

Let us define the oddness of a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n} as \sum_{i = 1}^n |i - p_i|.

Find the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

Constraints

* All values in input are integers.
* 1 \leq n \leq 50
* 0 \leq k \leq n^2

Input

Input is given from Standard Input in the following format:

n k

Output

Print the number of permutations of {1,\ 2,\ ...,\ n} of oddness k, modulo 10^9+7.

Examples

Input

3 2

Output

2

Input

39 14

Output

74764168

```python
def main():

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """

    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor

        Args:
            n (long): number to be resolved into factors

        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.

        Args:
            n (long): number
            r (long): number

        Raises:
            Exception: not defined when n or r is negative

        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.

        Args:
            n (long): number
            r (long): number

        Raises:
            Exception: not defined when n or r is negative

        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]

        Args:
            x (long): current minimum value
            y (long): potential minimum value

        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]

        Args:
            x (long): current maximum value
            y (long): potential maximum value

        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)

    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array, use [[0] * N for _ in range(N)]
    # set inputs
        # open(0).read() is a convenient method:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions used
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    if __name__ != '__main__':
        # for test
        sys.stdin = open('sample.txt')

    # ----------------------------------
    # main

    N, K = R()
    dp = [[[0]*3100 for _ in range(51)] for _ in range(51)]
    dp[0][0][0] = 1
    for i, rest, k in product(range(N), range(N), range(K+1)):
        dp[i+1][rest+1][k+2*rest+2] = (dp[i+1][rest+1][k+2*rest+2] + dp[i][rest][k]) % MOD
        if rest:
            dp[i+1][rest][k+2*rest] = (dp[i+1][rest][k+2*rest] + dp[i][rest][k] * 2 * rest) % MOD
        dp[i+1][rest][k+2*rest] = (dp[i+1][rest][k+2*rest] + dp[i][rest][k]) % MOD
        if rest:
            dp[i+1][rest-1][k+2*rest-2] = (dp[i+1][rest-1][k+2*rest-2] + dp[i][rest][k] * rest * rest) % MOD
    print(dp[N][0][K])

    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # for
    for k, v in Dic.items():
    """

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


p03110 AtCoder Beginner Contest 119 - Digital Gifts

Takahashi received otoshidama (New Year's money gifts) from N of his relatives.

You are given N values x_1, x_2, ..., x_N and N strings u_1, u_2, ..., u_N as input. Each string u_i is either `JPY` or `BTC`, and x_i and u_i represent the content of the otoshidama from the i-th relative.

For example, if x_1 = `10000` and u_1 = `JPY`, the otoshidama from the first relative is 10000 Japanese yen; if x_2 = `0.10000000` and u_2 = `BTC`, the otoshidama from the second relative is 0.1 bitcoins.

If we convert the bitcoins into yen at the rate of 380000.0 JPY per 1.0 BTC, how much are the gifts worth in total?

Constraints

* 2 \leq N \leq 10
* u_i = `JPY` or `BTC`.
* If u_i = `JPY`, x_i is an integer such that 1 \leq x_i \leq 10^8.
* If u_i = `BTC`, x_i is a decimal with 8 decimal digits, such that 0.00000001 \leq x_i \leq 100.00000000.

Input

Input is given from Standard Input in the following format:

N
x_1 u_1
x_2 u_2
:
x_N u_N

Output

If the gifts are worth Y yen in total, print the value Y (not necessarily an integer).

Output will be judged correct when the absolute or relative error from the judge's output is at most 10^{-5}.

Examples

Input

2
10000 JPY
0.10000000 BTC

Output

48000.0

Input

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Output

138000000.0038

```python
n=int(input())
ans=0
for _ in range(n):
    x,u=input().split()
    if u=='JPY': ans+=int(x)
    else: ans+=float(x)*38e4
print(ans)
```


p03257 AtCoder Grand Contest 027 - Modulo Matrix

You are given an integer N.

Construct any one N-by-N matrix a that satisfies the conditions below. It can be proved that a solution always exists under the constraints of this problem.

* 1 \leq a_{i,j} \leq 10^{15}
* a_{i,j} are pairwise distinct integers.
* There exists a positive integer m such that the following holds: Let x and y be two elements of the matrix that are vertically or horizontally adjacent. Then, {\rm max}(x,y) {\rm mod} {\rm min}(x,y) is always m.

Constraints

* 2 \leq N \leq 500

Input

Input is given from Standard Input in the following format:

N

Output

Print your solution in the following format:

a_{1,1} ... a_{1,N}
:
a_{N,1} ... a_{N,N}

Output

Print your solution in the following format:

a_{1,1} ... a_{1,N}
:
a_{N,1} ... a_{N,N}

Example

Input

2

Output

4 7
23 10

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

import random, math, fractions

def lcm(a, b):
    return (a // fractions.gcd(a, b)) * b

def is_prime(n):
    i = 2
    while i * i <= n:
        if n % i == 0:
            return False
        i += 1
    return True

def primes(n):
    lst = []
    for i in range(2, n + 1):
        if is_prime(i):
            lst.append(i)
    return lst

n = int(input())

a = [[None for j in range(n)] for i in range(n)]

lst = [(i,j) for i in range(n) for j in range(n - 1, -1, -1)]

used = set()
pr = primes(10 ** 4)

off = 0
while pr[off] < n + 3:
    off += 1

for (i, j) in lst:
    if (i + j) % 2 == 0:
        A = (i + j) // 2
        B = n + (i - j) // 2
        a[i][j] = (A + 1) * (pr[off + B])
        if a[i][j] in used:
            print(101, a[i][j])
            raise ValueError()
        used.add(a[i][j])

for (i, j) in lst:
    if (i + j) % 2 == 0:
        continue

    val = 1
    for (ip, jp) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
        if 0 <= ip < n and 0 <= jp < n and a[ip][jp] != None:
            val = lcm(val, a[ip][jp])

    if val >= 5 * 10 ** 14:
        print("ERR", val)
        raise ValueError()

    res = val + 1
    while res in used:
        k = random.randint(1, (10 ** 15 - 1) // val)
        res = k * val + 1

    a[i][j] = res
    used.add(res)

for i in range(n):
    print(" ".join(map(str, a[i])))

```


p03413 AtCoder Regular Contest 092 - Both Sides Merger

You have an integer sequence of length N: a_1, a_2, ..., a_N.

You repeatedly perform the following operation until the length of the sequence becomes 1:

* First, choose an element of the sequence.
* If that element is at either end of the sequence, delete the element.
* If that element is not at either end of the sequence, replace the element with the sum of the two elements that are adjacent to it. Then, delete those two elements.

You would like to maximize the final element that remains in the sequence.

Find the maximum possible value of the final element, and the way to achieve it.

Constraints

* All input values are integers.
* 2 \leq N \leq 1000
* |a_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

* In the first line, print the maximum possible value of the final element in the sequence.
* In the second line, print the number of operations that you perform.
* In the (2+i)-th line, if the element chosen in the i-th operation is the x-th element from the left in the sequence at that moment, print x.
* If there are multiple ways to achieve the maximum value of the final element, any of them may be printed.

Examples

Input

5
1 4 3 7 5

Output

11
3
1
4
2

Input

4
100 100 -1 100

Output

200
2
3
1

Input

6
-1 -2 -3 1 2 3

Output

4
3
2
1
2

Input

9
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Output

5000000000
4
2
2
2
2

```python
def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    N = I()
    A = LI()
    ans = -inf

    S = [0]*(N+1)
    fr = [-1]*N
    best = -1

    for i,a in enumerate(A):
        S[i] = a
        for j in range(i):
            if ((i-j)%2==0):
                if (S[j]+a>S[i]):
                    fr[i] = j
                    S[i] = S[j] + a
            if (S[i]>ans):
                ans = S[i]
                best = i
    #print(best)
    V = []
    for i in range(best+1,N)[::-1]:
        V.append(i+1)
    i = best
    while(fr[i]>=0):
        f = fr[i]
        #print(i,f)
        while(f<i):
            V.append(1+(i+f)//2)
            i -= 2
    for _ in range(i):
        V.append(1)

    print(ans)
    print(len(V))
    for v in V:
        print(v)
    return

def examF():
    ans = 0
    print(ans)
    return

from decimal import getcontext,Decimal as dec
import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def DI(): return dec(input())
def LDI(): return list(map(dec,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = dec("0.000000000001")
alphabet = [chr(ord('a') + i) for i in range(26)]
alphabet_convert = {chr(ord('a') + i): i for i in range(26)}

getcontext().prec = 28

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examE()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""
```


p03573 AtCoder Beginner Contest 075 - One out of Three

You are given three integers, A, B and C.
Among them, two are the same, but the remaining one is different from the rest.
For example, when A=5,B=7,C=5, A and C are the same, but B is different.
Find the one that is different from the rest among the given three integers.

Constraints

* -100 \leq A,B,C \leq 100
* A, B and C are integers.
* The input satisfies the condition in the statement.

Input

Input is given from Standard Input in the following format:

A B C

Output

Among A, B and C, print the integer that is different from the rest.

Examples

Input

5 7 5

Output

7

Input

1 1 7

Output

7

Input

-100 100 100

Output

-100

```python
a,b,c=map(int,input().split())
print((b==c)*a+(c==a)*b+(a==b)*c)
```


p03728 AtCoder Grand Contest 014 - Strange Sorting

Takahashi loves sorting.

He has a permutation (p_1,p_2,...,p_N) of the integers from 1 through N. Now, he will repeat the following operation until the permutation becomes (1,2,...,N):

* First, we will define high and low elements in the permutation, as follows. The i-th element in the permutation is high if the maximum element between the 1-st and i-th elements, inclusive, is the i-th element itself, and otherwise the i-th element is low.
* Then, let a_1,a_2,...,a_k be the values of the high elements, and b_1,b_2,...,b_{N-k} be the values of the low elements in the current permutation, in the order they appear in it.
* Lastly, rearrange the permutation into (b_1,b_2,...,b_{N-k},a_1,a_2,...,a_k).

How many operations are necessary until the permutation is sorted?

Constraints

* 1 ≤ N ≤ 2×10^5
* (p_1,p_2,...,p_N) is a permutation of the integers from 1 through N.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print the number of operations that are necessary until the permutation is sorted.

Examples

Input

5
3 5 1 2 4

Output

3

Input

5
5 4 3 2 1

Output

4

Input

10
2 10 5 7 3 6 4 9 8 1

Output

6

```python
N = int(input())
P = list(map(int, input().split()))

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

Pi = [0] * (N + 1)
for i, n in enumerate(P, 1):
    Pi[n] = i

T = [0] * N
f = [0] * N

if Pi[N] > Pi[N - 1]:
    T[N - 1] = 0
    f[N - 1] = N - 1
else:
    T[N - 1] = 1
    f[N - 1] = N

for i in range(N - 2, 0, -1):
    if T[i + 1] == 0:
        i_i = Pi[i]
        i_ii = Pi[i + 1]
        if i_ii > i_i:
            T[i] = T[i + 1]
            f[i] = f[i + 1]
        else:
            T[i] = T[i + 1] + 1
            f[i] = i + 1
    else:
        i_f = Pi[f[i + 1]]
        i_i = Pi[i]
        i_ii = Pi[i + 1]
        if i_f < i_i < i_ii or i_ii < i_f < i_i or i_i < i_ii < i_f:
            T[i] = T[i + 1]
            f[i] = f[i + 1]
        else:
            T[i] = T[i + 1] + 1
            f[i] = i + 1

print(T[1])
```


p03892 CODE FESTIVAL 2016 Relay (Parallel) - Segment on Grid Paper

Takahashi is drawing a segment on grid paper.

From a certain square, a square that is x squares to the right and y squares above, is denoted as square (x, y).

When Takahashi draws a segment connecting the lower left corner of square (A, B) and the lower left corner of square (C, D), find the number of the squares crossed by the segment.

Here, the segment is said to cross a square if the segment has non-empty intersection with the region within the square, excluding the boundary.

Constraints

* 1 \leq A, B, C, D \leq 10^9
* At least one of A \neq C and B \neq D holds.

Input

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

A B C D

Output

Print the number of the squares crossed by the segment.

Examples

Input

1 1 3 4

Output

4

Input

2 3 10 7

Output

8

```python
a,b,c,d = (int(i) for i in input().split())
def gcd(x,y):
	if x%y==0: return y
	else: return gcd(y,x%y)
if a==c or b==d: ans = 0
else:
	n = gcd(abs(a-c),abs(b-d))
	e,f = abs(a-c)//n,abs(b-d)//n
	ans = (e+f-1)*n
print(ans)
```


p04051 AtCoder Grand Contest 001 - BBQ Hard

Snuke is having another barbeque party.

This time, he will make one serving of Skewer Meal.

He has a stock of N Skewer Meal Packs. The i-th Skewer Meal Pack contains one skewer, A_i pieces of beef and B_i pieces of green pepper. All skewers in these packs are different and distinguishable, while all pieces of beef and all pieces of green pepper are, respectively, indistinguishable.

To make a Skewer Meal, he chooses two of his Skewer Meal Packs, and takes out all of the contents from the chosen packs, that is, two skewers and some pieces of beef or green pepper. (Remaining Skewer Meal Packs will not be used.) Then, all those pieces of food are threaded onto both skewers, one by one, in any order.

(See the image in the Sample section for better understanding.)

In how many different ways can he make a Skewer Meal? Two ways of making a Skewer Meal is different if and only if the sets of the used skewers are different, or the orders of the pieces of food are different. Since this number can be extremely large, find it modulo 10^9+7.

Constraints

* 2≦N≦200,000
* 1≦A_i≦2000, 1≦B_i≦2000

Input

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

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the number of the different ways Snuke can make a serving of Skewer Meal, modulo 10^9+7.

Example

Input

3
1 1
1 1
2 1

Output

26

```python
mod = 10**9+7
mod2 = 998244353
rng = 100100
fctr = [1]
finv = [1]
for i in range(1,rng):
  fctr.append(fctr[-1]*i%mod)
for i in range(1,rng):
  finv.append(pow(fctr[i],mod-2,mod))
def cmb(n,k):
  if n<0 or k<0:
    return 0
  else:
    return fctr[n]*finv[n-k]*finv[k]%mod
n = int(input())
ab = [list(map(int,input().split())) for i in range(n)]
s = 0
for a,b in ab:
  s = max(s,a,b)
dp = [[0 for i in range(2*s+2)] for j in range(2*s+2)]
for a,b in ab:
  dp[s+1-a][s+1-b] += 1
for i in range(1,2*s+2):
  for j in range(1,2*s+2):
    dp[i][j] = (dp[i][j]+dp[i-1][j]+dp[i][j-1])%mod
x = 0
for a,b in ab:
  x = (x+dp[s+1+a][s+1+b])%mod
t = 0
for a,b in ab:
  t = (t+cmb(2*a+2*b,2*a))%mod
ans = (x-t)*pow(2,mod-2,mod)%mod
print(ans)
```


p00130 Train

There are trains with 26 cars or less. Each vehicle has an identification code from lowercase a to z. No vehicle has the same symbol. However, the order in which the vehicles are connected is arbitrary. The conductor patrols the train. The conductor patrolls back and forth in the train, so he may pass through the same vehicle many times. However, all vehicles shall be patrolled at least once. In addition, the vehicle that starts the patrol and the vehicle that finishes the patrol is not necessarily the vehicle at the end of the train.

There is a patrol record of all the trains on which an Aru Shashou is on board. Create a program that outputs the formation of each train that can be seen from it from the lead car. The patrol record corresponds to one train per line. Each line consists of a string of lowercase letters separated by <-or->. <-Represents a move to a vehicle in front, and-> represents a move to a vehicle behind.

For example, a-> b <-a <-c means that vehicle a has moved to the vehicle behind b, b has moved to a ahead, and a has moved to c ahead. In this case, the train formation will be cab from the first car.

Input

The number of patrol records n (n ≤ 50) is given to the first line, and the character string si (half-width character string up to 1024 characters) representing the patrol record i is given to the following n lines.

Output

For patrol record i, output the character string indicating the formation of the train from the first car on the i-line.

Examples

Input

4
a->e->c->b->d
b

Output

aecbd
edacb
bacde
bcdae

Input

4
a->e->c->b->d
b<-c<-a<-d<-e
b->a->c<-a->c->d<-c<-a<-b->a->c->d->e<-d
a->e<-a<-d->a->e<-a<-d<-c->d->a<-d<-c<-b->c->d<-c

Output

aecbd
edacb
bacde
bcdae

```python
for _ in range(int(input())):
    s=list(input())
    word,direct=[],""
    for i in s:
        if i.isalpha():
            if direct==">":
                if i not in word:word.append(i)
            else:
                if i not in word:word.insert(0,i)
        elif i=="<" or i==">":direct=i
    print(*word,sep="")

```


p00263 Kongo Type

Consider a 32-bit real type with 7 bits from the right as the decimal part, the following 24 bits as the integer part, and the leftmost 1 bit as the sign part as shown below (b1, ..., b32). Represents 0 or 1).

<image>

To translate this format into a decimal representation that is easy for humans to understand, interpret it as follows.
(-1) Sign part × (integer part + decimal part)

In the above expression, the value of the integer part is b8 + 21 x b9 + 22 x b10 + ... + 223 x b31. For example, the integer part is

<image>

If it looks like, the value of the integer part is calculated as follows.
1 + 21 + 23 = 1 + 2 + 8 = 11

On the other hand, the value of the decimal part is (0.5) 1 × b7 ＋ (0.5) 2 × b6 ＋ ... ＋ (0.5) 7 × b1. For example, the decimal part

<image>

If it looks like, the decimal part is calculated as follows.
0.51 + 0.53 = 0.5 + 0.125 = 0.625

Furthermore, in the case of the following bit string that combines the sign part, the integer part, and the decimal part,

<image>

The decimal number represented by the entire bit string is as follows (where -1 to the 0th power is 1).
(-1) 0 × (1 + 2 + 8 + 0.5 + 0.125) = 1 × (11.625) = 11.625

If you enter Q 32-bit bit strings, create a program that outputs the real decimal notation represented by those bit strings without any error.

input

The input consists of one dataset. Input data is given in the following format.

Q
s1
s2
..
..
..
sQ

The number of bit strings Q (1 ≤ Q ≤ 10000) is given in the first row. The input bit string si is given in the following Q row. Suppose the input bit string is given in hexadecimal notation (for example, 0111 1111 1000 1000 0000 0000 0000 0000 is given as 7f880000). In other words, each of the Q lines contains eight hexadecimal numbers, which are 4-bit binary numbers, without any blanks. The table below shows the correspondence between decimal numbers, binary numbers, and hexadecimal numbers.

<image>

Hexadecimal letters a through f are given in lowercase.

output

Outputs the real decimal notation represented by each bit string line by line. However, in the decimal part, if all the digits after a certain digit are 0, the digits after that digit are omitted. As an exception, if the decimal part is 0, one 0 is output to the decimal part.

Example

Input

8
00000000
80000000
00000080
00000040
000000c0
00000100
80000780
80000f70

Output

0.0
-0.0
1.0
0.5
1.5
2.0
-15.0
-30.875

```python
q = int(input())
for _ in range (q):
    bits = F'{int(input(), 16):32b}'
    sign = '-' if bits[0] == '1' else ''
    integer = sum([2**i for i, b in enumerate(bits[1:25][::-1]) if b == '1'])
    fraction = sum([0.5**i for i, b in enumerate(bits[25:], start=1) if b == '1'])
    print(sign + str(float(integer + fraction)))

```


p00450 Setting Go Stones

problem

Play by arranging white and black stones on the table. First, place the stones on the left edge of the table. Then place the stones in the second place from the left. Repeat this n times to arrange n stones in a horizontal row. However, when placing a new i-th go stone, replace the go stone on the table according to the following rules.

* If i is odd: Do not replace the stones that were on the table, but place the new stones i-th from the left.
* If i is even: If the color of the new go stone placed i-th from the left and the color of the rightmost go stone on the table are the same, the go stone on the table is not replaced and the new go stone is placed i-th from the left. If this is not the case, that is, if the color of the new i-th go stone from the left is different from the color of the right-most go stone on the table, first remove all the consecutive right-end go stones of the same color on the table, and then use the i-th go stone. Replace with a go stone of the same color, and place the i-th go stone on the right edge of the table.

For example, when the first 7 go stones are placed,

○○ ●● ○○○

(○ represents white go stones, ● represents black go stones.)

* If the 8th go stone is white (○), it is the same color as the rightmost go stone, so leave it as it is. Therefore, the go stone on the table is

○○ ●● ○○○○

Will be.
* If the 8th go stone is black (●), the color is different from the rightmost go stone (○), so first remove the 3 consecutive white go stones (○) on the right end of the table, and then remove the black go stone (●). And put the eighth go stone on the far right. Therefore, the go stone on the table

○○ ●●●●●●

Will be.

Given the order of the stones to be placed as input, create a program to find the number of white stones placed on the table after arranging n stones.

input

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

A positive integer n (1 ≤ n ≤ 100000) is written on the first line. In the second and subsequent lines i + 1 (1 ≤ i ≤ n), the color of the go stone placed in the i-th position is written. The integer ci is written, and if ci is 0, it means that the color of the i-th go stone is white, and if it is 1, it means that the color of the i-th go stone is black.

Of the scoring data, 50% of the points are given by satisfying n ≤ 10000.

When n is 0, it indicates the end of input. The number of datasets does not exceed 10.

output

For each dataset, output the number of white stones placed on the table after arranging n stones in one line.

Examples

Input

8
1
0
1
1
0
0
0
0
8
1
0
1
1
0
0
0
1
0

Output

6
2

Input

None

Output

None

```python
while True:
    n = int(input())
    if n==0: break
    edge = 0
    sq = 0
    past = []

    for i in range(n):
        nxt = int(input())
        if i==0:
            edge = nxt

        if i%2 == 0:
            if nxt == edge:
                sq += 1
            else:
                edge = nxt
                past.append(sq)
                sq = 1
        else:
            if nxt == edge:
                sq += 1
            else:
                edge = nxt
                sq += 1
                if len(past) != 0:
                    sq += past.pop()
    past.append(sq)

    answer = 0
    for i in range(len(past)):
        if edge == 0:
            answer += past[-i-1]
        edge = 1 - edge

    print(answer)
```


p00641 Huge Family

Mr. Dango's family has extremely huge number of members. Once it had about 100 members, and now it has as many as population of a city. It is jokingly guessed that the member might fill this planet in near future. They all have warm and gracious personality and are close each other.

They usually communicate by a phone. Of course, They are all taking a family plan. This family plan is such a thing: when a choose b, and b choose a as a partner, a family plan can be applied between them and then the calling fee per unit time between them discounted to f(a, b), which is cheaper than a default fee. Each person can apply a family plan at most 2 times, but no same pair of persons can apply twice. Now, choosing their partner appropriately, all members of Mr. Dango's family applied twice.

Since there are huge number of people, it is very difficult to send a message to all family members by a phone call. Mr. Dang have decided to make a phone calling network that is named 'clan' using the family plan. Let us present a definition of clan.

Let S be an any subset of all phone calls that family plan is applied. Clan is S such that:

1. For any two persons (let them be i and j), if i can send a message to j through phone calls that family plan is applied (directly or indirectly), then i can send a message to j through only phone calls in S (directly or indirectly).
2. Meets condition 1 and a sum of the calling fee per unit time in S is minimized.

Clan allows to send a message efficiently. For example, we suppose that one have sent a message through all calls related to him in the clan. Additionaly we suppose that every people follow a rule, "when he/she receives a message through a call in clan, he/she relays the message all other neibors in respect to clan." Then, we can prove that this message will surely be derivered to every people that is connected by all discounted calls, and that the message will never be derivered two or more times to same person.

By the way, you are given information about application of family plan of Mr. Dango's family. Please write a program that calculates that in how many ways a different clan can be constructed. You should output the answer modulo 10007 because it may be very big.

Constraints

* 3 ≤ n ≤ 100,000

Input

The input consists of several datasets.

The first line of each dataset contains an integer n, which indicates the number of members in the family.

Next n lines represents information of the i-th member with four integers. The first two integers respectively represent b[0] (the partner of i) and f(i, b[0]) (the calling fee per unit time between i and b[0]). The following two integers represent b[1] and f(i, b[1]) in the same manner.

Input terminates with a dataset where n = 0.

Output

For each dataset, output the number of clan modulo 10007.

Example

Input

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

Output

1
2

```python
# AOJ 1055 Huge Family
# Python3 2018.7.7 bal4u

# UNION-FIND library
class UnionSet:
	def __init__(self, nmax):
		self.size = [1]*nmax
		self.id = [i for i in range(nmax+1)]
	def root(self, i):
		while i != self.id[i]:
			self.id[i] = self.id[self.id[i]]
			i = self.id[i]
		return i
	def connected(self, p, q): return self.root(p) == self.root(q)
	def unite(self, p, q):
		i, j = self.root(p), self.root(q)
		if i == j: return
		if self.size[i] < self.size[j]:
			self.id[i] = j
			self.size[j] += self.size[i]
		else:
			self.id[j] = i
			self.size[i] += self.size[j]
# UNION-FIND library

def check(k, f):
	if cnt[k] == 0 or f > vmax[k]: cnt[k], vmax[k] = 1, f
	elif f == vmax[k]: cnt[k] += 1

while True:
	n = int(input())
	if n == 0: break
	u = UnionSet(n)
	f = [[0 for j in range(2)] for i in range(n)]
	cnt, vmax = [0]*n, [0]*n
	for i in range(n):
		a, f[i][0], b, f[i][1] = map(int, input().split())
		u.unite(i, a)
		u.unite(i, b)
	for i in range(n):
		k = u.root(i)
		check(k, f[i][0])
		check(k, f[i][1])
	ans = 1
	for i in range(n):
		if cnt[i]: ans = ans * (cnt[i] >> 1) % 10007
	print(ans)

```


p00917 Clock Hands

We have an analog clock whose three hands (the second hand, the minute hand and the hour hand) rotate quite smoothly. You can measure two angles between the second hand and two other hands.

Write a program to find the time at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on or after a given time.

<image>
Figure D.1. Angles between the second hand and two other hands

Clocks are not limited to 12-hour clocks. The hour hand of an H-hour clock goes around once in H hours. The minute hand still goes around once every hour, and the second hand goes around once every minute. At 0:0:0 (midnight), all the hands are at the upright position.

Input

The input consists of multiple datasets. Each of the dataset has four integers H, h, m and s in one line, separated by a space. H means that the clock is an H-hour clock. h, m and s mean hour, minute and second of the specified time, respectively.

You may assume 2 ≤ H ≤ 100, 0 ≤ h < H, 0 ≤ m < 60, and 0 ≤ s < 60.

The end of the input is indicated by a line containing four zeros.

<image>
Figure D.2. Examples of H-hour clock (6-hour clock and 15-hour clock)

Output

Output the time T at which "No two hands overlap each other" and "Two angles between the second hand and two other hands are equal" for the first time on and after the specified time.

For T being ho:mo:so (so seconds past mo minutes past ho o'clock), output four non-negative integers ho, mo, n, and d in one line, separated by a space, where n/d is the irreducible fraction representing so. For integer so including 0, let d be 1.

The time should be expressed in the remainder of H hours. In other words, one second after (H − 1):59:59 is 0:0:0, not H:0:0.

Example

Input

12 0 0 0
12 11 59 59
12 1 56 0
12 1 56 3
12 1 56 34
12 3 9 43
12 3 10 14
12 7 17 58
12 7 18 28
12 7 23 0
12 7 23 31
2 0 38 29
2 0 39 0
2 0 39 30
2 1 6 20
2 1 20 1
2 1 20 31
3 2 15 0
3 2 59 30
4 0 28 48
5 1 5 40
5 1 6 10
5 1 7 41
11 0 55 0
0 0 0 0

Output

0 0 43200 1427
0 0 43200 1427
1 56 4080 1427
1 56 47280 1427
1 57 4860 1427
3 10 18600 1427
3 10 61800 1427
7 18 39240 1427
7 18 82440 1427
7 23 43140 1427
7 24 720 1427
0 38 4680 79
0 39 2340 79
0 40 0 1
1 6 3960 79
1 20 2400 79
1 21 60 79
2 15 0 1
0 0 2700 89
0 28 48 1
1 6 320 33
1 6 40 1
1 8 120 11
0 55 0 1

```python
import sys
def gcd(m, n):
    while n:
        m, n = n, m % n
    return m
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
    f = lambda h, m, s: 3600*h + 60*m + s
    H, h, m, s = map(int, readline().split())
    if H == 0:
        return False
    d0 = f(h, m, s)
    M = f(H, 0, 0)
    res = []
    for h0 in range(H):
        for m0 in range(60):
            p = 3600*h0 + 60*m0 + 60*H*m0; q = 119*H-1
            for d in [-3600*H, 0, 3600*H]:
                p1 = p + d; q1 = q
                g = gcd(p1, q); p1 //= g; q1 //= g
                if 0 <= p1 < 60*q1:
                    if H*(60*m0*q1 + p1) != q1*(3600*h0 + 60*m0) + p1:
                        res.append((f(h0, m0, 0) + p1/q1, h0, m0, p1, q1))
    res.sort(key = lambda x: (x[0] - d0) % M)
    _, h, m, p, q = res[0]
    write("%d %d %d %d\n" % (h, m, p, q))
    return True
while solve():
    ...

```


p01050 String Compression

Problem

Given the string S, which consists of lowercase letters and numbers. Follow the steps below to compress the length of string S.

1. Change the order of the characters in the character string to any order.
Example: "0ig3he12fz99"-> "efghiz012399"
2. Perform the following operations any number of times.

* Select a contiguous substring of "abcdefghijklmnopqrstuvwxyz" in the string and replace it with (first character)'-' (last character).
Example: "efghiz012399"-> "e-iz012399"
* Select a string with a tolerance of 1 (a continuous substring of "0123456789") in the string and replace it with (first digit)'-' (last digit).
Example: "e-iz012399"-> "e-iz0-399"

Find the minimum length of the string obtained by compressing the string S.

Constraints

* 1 ≤ | S | ≤ 100
* String S contains only lowercase letters and numbers

Input

The string S is given on one line.

Output

Output the minimum value of the length of the character string obtained by compressing the character string S on one line. If it cannot be compressed, output the length of the original string S.

Examples

Input

0ig3he12fz99

Output

9

Input

1122334455

Output

6

```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from collections import defaultdict

S = input()
S = sorted(S)
S = list(map(ord, S))

ans = 0
while len(S) > 0:
    mn = S[0]
    S.remove(mn)
    nxt = mn + 1
    succ = 1
    while True:
        if nxt in S:
            S.remove(nxt)
            succ += 1
            nxt += 1
        else:
            break
    ans += min(3, succ)
print(ans)
```


p01319 Canal: Water Going Up and Down

ACM countries have rivers that flow from east to west in the center. This river flows from the neighboring country in the west through the neighboring country in ACM to the neighboring country in the east, and the total length in ACM is K km. It is planned to install several locks on this river and use it as a canal.

A lock is a mechanism for a ship to move between two different water levels. Locks have locks on the upstream and downstream sides, respectively, and a small body of water called a lock chamber between them. After putting the ship in this lock room, water is injected or drained, and the water level in the lock room is raised or lowered to raise or lower the ship. The schematic diagram is shown below.

<image>
Figure F-1: Schematic diagram of the lock

Since the width of this river is not very wide, it has been decided that it will be a one-way canal from west to east. The person in charge of design wants to optimize the location of the lock according to the expected navigation schedule of the ship in order to operate the canal efficiently.

You are a programmer hired by a designer. Your job is to write a program that simulates the time it takes for all ships to cross the river, given the lock information and the navigation schedules for multiple ships.

Each lock is represented by the following information.

* Distance from the western end of ACM country X (km)
* Volume of water required to switch the water level L (L)
* Maximum water injection amount per unit time F (L / h)
* Maximum displacement per unit time D (L / h)
* Hierarchical relationship between the water level on the west side and the water level on the east side of the lock

For convenience, in the simulation, it is assumed that the river continues infinitely outside the ACM as well.

At the start of the simulation, the water levels in all the lock chambers are the lower of the eastern and western water levels. In addition, the ships included in the navigation schedule shall be lined up every 1 km from east to west in the order given by input, starting from the western end of the ACM country. For convenience, the initial position of the leading ship is set to the 0km point.

As soon as the simulation starts, the ship begins to sail east. At this time, no other ship should enter less than 1km before and after one ship. The maximum speed V (km / h) is set for each ship. The ship can reach any speed in an instant and even stand still in an instant. Basically, a ship sails at the maximum speed, but if the following ship has a faster maximum speed than the preceding ship and the following ship catches up 1 km before the preceding ship, the following ship will lead. It sails at the same speed as the ship. The size of the ship and locks shall be negligible.

A ship can enter the lock only when the water level on the west side of the lock is equal to the water level in the lock chamber. Similarly, you can exit the lock only when the water level on the east side of the lock is equal to the water level in the lock chamber. If there is no ship inside, the water level in each lock will rise or fall until it matches the water level on the west side of the lock. If there is a ship, it will be displaced until it matches the water level on the east side of the lock. Even if the ship is moored just 1km away from the lock, the ship can leave the lock. However, at this time, the ship must berth at the exit from the lock until the preceding ship starts.

After passing the eastern end of the ACM country, the ship sails to infinity as fast as possible. The simulation ends when all ships have passed the eastern end of the ACM country.

Input

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

> NMK
> X1 L1 F1 D1 UD1
> X2 L2 F2 D2 UD2
> ...
> XN LN FN DN UDN
> V1
> V2
> ...
> VM
>

The first line consists of three integers N, M, K. N (1 ≤ N ≤ 100) is the number of locks, M (1 ≤ M ≤ 100) is the number of ships, and K (2 ≤ K ≤ 1000) is the total length of the river in ACM.

The following N lines represent lock information. Each line consists of 5 integers Xi, Li, Fi, Di, UDi. Xi (1 ≤ Xi ≤ K -1) is the position of lock i from the western end of the ACM country (km), Li (1 ≤ Li ≤ 1000) is the volume of water required to switch the water level of lock i (L), Fi (1 ≤ Fi ≤ 1000) is the maximum water injection amount per unit time of lock i (L / h), Di (1 ≤ Di ≤ 1000) is the maximum drainage amount per unit time of lock i (L / h), UDi ( UDi ∈ {0, 1}) represents the hierarchical relationship between the water level on the west side and the water level on the east side of the lock i, respectively. When UDi is 0, the lock i means that the water level is higher on the east side than on the west side. On the other hand, when UDi is 1, lock i means that the water level is lower on the east side than on the west side.

The following M rows are given the integer Vi (1 ≤ Vi ≤ 1000), which represents the maximum speed (km / h) of the i-th vessel in each row.

Locks are given in ascending order of Xi values. In addition, multiple locks will not be installed at the same position.

The end of the input consists of three zeros separated by spaces.

Output

For each dataset, output the time from the start to the end of the simulation in one line. The output value may contain an error of 10-6 or less. The value may be displayed in any number of digits after the decimal point.

Example

Input

1 1 100
50 200 20 40 0
1
2 4 100
7 4 1 4 1
19 5 1 4 0
5
3
7
9
1 2 3
1 1 1 1 0
1
3
1 2 10
5 10 1 1 1
2
3
0 0 0

Output

110
46.6666666667
5
41.6666666667

```python
while True:
    n, m, k = (int(s) for s in input().split())
    if (n, m, k) == (0, 0, 0):
        break

    t_out = [0.] * (k + m + 1)
    tl_east = [0.] * (k + m + 1)
    tl_west = [0.] * (k + m + 1)

    for i in range(n):
        xi, li, fi, di, udi = (int(s) for s in input().split())
        if not udi:
            tl_east[xi] = li / fi
            tl_west[xi] = li / di
            t_out[xi] = -tl_west[xi]
        else:
            tl_east[xi] = li / di
            tl_west[xi] = li / fi

    for i in range(m):
        vi = int(input())
        t_out[0] = max(t_out[1] - tl_east[1], i / vi)
        for j in range(1, k + m):
            t_out[j] = tl_east[j] + max(t_out[j - 1] + 1 / vi,
                                        t_out[j] + tl_west[j],
                                        t_out[j + 1] - tl_east[j + 1])

    print(t_out[k])
```


p01487 RabbitWalking

Example

Input

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

Output

11

```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write

def solve():
    N, M = map(int, readline().split())
    G = [[] for i in range(N)]
    for i in range(M):
        a, b = map(int, readline().split())
        G[a-1].append(b-1)
        G[b-1].append(a-1)
    col = [-1]*N
    C = {}
    L0 = 0
    L = 0
    for i in range(N):
        if col[i] != -1:
            continue
        que = deque([i])
        col[i] = 0
        cs = [1, 0]
        while que:
            v = que.popleft()
            c = col[v]^1
            for w in G[v]:
                if col[w] != -1:
                    if col[w] != c:
                        write("-1\n")
                        return
                else:
                    col[w] = c
                    cs[c] += 1
                    que.append(w)
        e = abs(cs[1] - cs[0])
        L += e
        if e > 0:
            C[e] = C.get(e, 0) + 1
    W = L//2
    dp = [0]*(W+1)
    dp[0] = 1
    for v, c in C.items():
        for b in range(v):
            s = 0
            k0 = (W - b) // v * v + b
            for i in range(c):
                if k0-v*i >= 0:
                    s += dp[k0-v*i]
            for k in range(k0, -1, -v):
                s -= dp[k]
                if k-c*v >= 0:
                    s += dp[k-c*v]
                if s:
                    dp[k] = 1
    k = 0
    for i in range(W, -1, -1):
        if dp[i]:
            k = i
            break
    A = (N - L) // 2 + k
    B = (N - L) // 2 + L - k
    write("%d\n" % (A*B - M))
solve()

```


p01934 Dimension travel

problem

Dimension exists from $ 1 $ dimension to $ N $ dimension. AOR Ika can move between dimensions. Specifically, when AOR Ika is in the $ i $ dimension, she can move freely to the $ j $ dimension ($ i> j $), but in the $ k $ dimension ($ i <k $). You need to use magic to move to.

AOR Ika can use $ M $ types of magic and is numbered $ 1, 2, \ dots, M $. The $ i $ th magic allows you to move from the $ a_i $ dimension to the $ b_i $ dimension. This can only be used when you are in the $ a_i $ dimension.

When you go to the $ i $ dimension, you will receive a dimension-specific "curse of dimensionality". AOR Ika takes $ d_i $ damage due to the "curse of dimensionality" of the $ i $ dimension. If you receive the "curse of dimensionality" of the $ i $ dimension, you will not receive the "curse of dimensionality" of the $ j $ dimension ($ i> j $) forever.

Find the minimum total damage inflicted when AOR Ika moves from the $ s $ dimension to the $ t $ dimension. However, AOR Ika-chan has already received the "curse of dimensionality" of the $ s $ dimension, and we will not consider the damage. Also, AOR Ika is guaranteed to be able to go to the $ t $ dimension.

output

Output the minimum value of the total damage received by AOR Ika-chan. Also, output a line break at the end.

Example

Input

3 1 2 3
1 2 3
1 3

Output

3

```python
# AOJ 2834 Dimension travel
# Python3 2018.7.12 bal4u

INF = 0x7fffffff
import heapq
def dijkstra(V, to, start, goal):
	dist = [INF]*V
	Q = []
	dist[start] = 0
	heapq.heappush(Q, (0, start))
	while Q:
		t, s = heapq.heappop(Q)
		if s == goal: break
		if dist[s] < t: continue
		for e in to[s]:
			nt = t
			if e > s: nt += d[e]
			if dist[e] > nt:
				dist[e] = nt
				heapq.heappush(Q, (nt, e))
	return t

import sys
N, M, s, t = map(int, input().split())
s, t = s-1, t-1
if s >= t: print(0); sys.exit(0)
d = list(map(int, input().split()))
to = [[i-1] if i > 0 else [] for i in range(N)]
for i in range(M):
	a, b = map(int, input().split())
	to[a-1].append(b-1)
print(dijkstra(N, to, s, t))

```


p02368 Strongly Connected Components

A direced graph is strongly connected if every two nodes are reachable from each other. In a strongly connected component of a directed graph, every two nodes of the component are mutually reachable.

Constraints

* 1 ≤ |V| ≤ 10,000
* 0 ≤ |E| ≤ 30,000
* 1 ≤ Q ≤ 100,000

Input

A directed graph G(V, E) and a sequence of queries where each query contains a pair of nodes u and v.

|V| |E|
s0 t0
s1 t1
:
s|E|-1 t|E|-1
Q
u0 v0
u1 v1
:
uQ-1 vQ-1

|V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target nodes of i-th edge (directed).

ui and vi represent a pair of nodes given as the i-th query.

Output

For each query, pinrt "1" if the given nodes belong to the same strongly connected component, "0" otherwise.

Example

Input

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

Output

1
0
1
1

```python
def solve():
    N, M = map(int, input().split())
    edges = [[] for _ in [0]*N]
    r_edges = [[] for _ in [0]*N]

    for _ in [0]*M:
        a, b = map(int, input().split())
        edges[a].append(b)
        r_edges[b].append(a)

    c = kosaraju(edges, r_edges)
    group = [0]*N
    for i in range(len(c)):
        for v in c[i]:
            group[v] = i

    result = []
    append = result.append
    for _ in [0]*int(input()):
        a, b = map(int, input().split())
        append("1" if group[a] == group[b] else "0")

    print("\n".join(result))

def kosaraju(edges, reverse_edges):
    import sys
    sys.setrecursionlimit(10**7)
    v_count = len(edges)
    order = [0]*v_count
    k = [1]

    def get_order(v):
        order[v] = 1
        [None for dest in edges[v] if order[dest] == 0 and get_order(dest)]
        order[v] = k[0]
        k[0] += 1

    def get_components(v):
        order[v] = 0
        return [v] + [_v for dest in reverse_edges[v] if order[dest] > 0 for _v in get_components(dest)]

    [None for v in range(v_count) if order[v] == 0 and get_order(v)]
    return [get_components(v) for v, _ in sorted(enumerate(order), key=lambda x: x[1], reverse=True) if order[v] > 0]

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