665_D. Simple Subset

A tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i, j) (1 ≤ i < j ≤ k), xi + xj is a prime.

You are given an array a with n positive integers a1, a2, ..., an (not necessary distinct). You want to find a simple subset of the array a with the maximum size.

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Let's define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it.

Input

The first line contains integer n (1 ≤ n ≤ 1000) — the number of integers in the array a.

The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a.

Output

On the first line print integer m — the maximum possible size of simple subset of a.

On the second line print m integers bl — the elements of the simple subset of the array a with the maximum size.

If there is more than one solution you can print any of them. You can print the elements of the subset in any order.

Examples

Input

2
2 3

Output

2
3 2

Input

2
2 2

Output

1
2

Input

3
2 1 1

Output

3
1 1 2

Input

2
83 14

Output

2
14 83

```python
n = int(input())
L = list(map(int, input().split()))
P = [-1 for _ in range(2000001)]

def premier(n):
    if P[n] >= 0:
        return P[n]
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            P[n] = False
            return False
    P[n] = True
    return True

e = L.count(1)
if n == 1:
    print(1)
    print(L[0])
elif e > 1:
    L.sort()
    i = 1
    while i < n and L[i] == 1:
        i += 1
    u = i
    ok = 0
    while i < n:
        if premier(L[i]+1):
            print(u+1)
            for j in range(u):
                print(1,end=" ")
            print(L[i])
            ok = 1
            break
        i += 1
    if ok == 0:
        print(u)
        for i in range(u):
            print(1,end=" ")
else:
    ok = 0
    for i in range(n-1):
        for j in range(i+1,n):
            t = premier(L[i]+L[j])
            if t:
                print(2)
                print(str(L[i])+" "+str(L[j]))
                ok = 1
                break
        if ok:
            break
    if ok == 0:
        print(1)
        print(L[0])

```


68_B. Energy exchange

It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by <image> units.

Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.

Input

First line of the input contains two integers n and k (1 ≤ n ≤ 10000, 0 ≤ k ≤ 99) — number of accumulators and the percent of energy that is lost during transfers.

Next line contains n integers a1, a2, ... , an — amounts of energy in the first, second, .., n-th accumulator respectively (0 ≤ ai ≤ 1000, 1 ≤ i ≤ n).

Output

Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy.

The absolute or relative error in the answer should not exceed 10 - 6.

Examples

Input

3 50
4 2 1

Output

2.000000000

Input

2 90
1 11

Output

1.909090909

```python
def check(a, k, cur):
	need = 0
	have = 0
	for x in a:
		if x < cur:
			need += cur - x
		else:
			have += (x - cur) * (1 - k / 100)
	return need <= have

n, k = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
l = 0
r = 1000
for i in range(100):
	cur = (l + r) / 2
	if check(a, k, cur):
		l = cur
	else:
		r = cur
print((l + r) / 2)

```


711_E. ZS and The Birthday Paradox

ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland.

In Udayland, there are 2n days in a year. ZS the Coder wants to interview k people from Udayland, each of them has birthday in one of 2n days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day.

ZS the Coder knows that the answer can be written as an irreducible fraction <image>. He wants to find the values of A and B (he does not like to deal with floating point numbers). Can you help him?

Input

The first and only line of the input contains two integers n and k (1 ≤ n ≤ 1018, 2 ≤ k ≤ 1018), meaning that there are 2n days in a year and that ZS the Coder wants to interview exactly k people.

Output

If the probability of at least two k people having the same birthday in 2n days long year equals <image> (A ≥ 0, B ≥ 1, <image>), print the A and B in a single line.

Since these numbers may be too large, print them modulo 106 + 3. Note that A and B must be coprime before their remainders modulo 106 + 3 are taken.

Examples

Input

3 2

Output

1 8

Input

1 3

Output

1 1

Input

4 3

Output

23 128

Note

In the first sample case, there are 23 = 8 days in Udayland. The probability that 2 people have the same birthday among 2 people is clearly <image>, so A = 1, B = 8.

In the second sample case, there are only 21 = 2 days in Udayland, but there are 3 people, so it is guaranteed that two of them have the same birthday. Thus, the probability is 1 and A = B = 1.

```python
#copied
import math
n, k = [int(x) for x in input().split()]
if n<70 and k>2**n:
    print(1,1)
    exit(0)
mod = int(1e6)+3

def fastpow(a,b):
    t, ans = a, 1
    while b:
        if(b&1):
            ans = ans*t%mod
        t = t*t %mod
        b>>=1
    return ans

t=k-1
cnt=0
while t: # gets highest possible pow that divides
    cnt += t>>1
    t>>=1

x=0
t=fastpow(2,n)
if k<mod:
    x=1
    for i in range(1,k):
        x = x*(t-i)%mod
y=fastpow(2,n*(k-1))

inv = fastpow(2,mod-2)
inv = fastpow(inv,cnt)

x=(x*inv%mod+mod)%mod
y=(y*inv%mod+mod)%mod

x=(y-x+mod)%mod

print(x,y)

```


778_B. Bitwise Formula

Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.

Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.

Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.

Input

The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000).

The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of:

  1. Binary number of exactly m bits.
  2. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter.

Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.

Output

In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.

Examples

Input

3 3
a := 101
b := 011
c := ? XOR b

Output

011
100

Input

5 1
a := 1
bb := 0
cx := ? OR a
d := ? XOR ?
e := d AND bb

Output

0
0

Note

In the first sample if Peter chooses a number 0112, then a = 1012, b = 0112, c = 0002, the sum of their values is 8. If he chooses the number 1002, then a = 1012, b = 0112, c = 1112, the sum of their values is 15.

For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.

```python
#from math import *
from sys import *
from decimal import *

def main():
    n,k=(int(z) for z in stdin.readline().split())
    d=[]
    nm=[0]*n
    bt1=[False]*(n+1)
    bt2=[False]*(n+1)
    bt2[-1]=True
    nam=dict()
    nam["?"]=-1
    for i in range(n):
        fl=0
        s=stdin.readline()[:-1].split(" := ")
        nam[s[0]]=i
        if len(s[1])<30:
            for j in s[1]:
                if j=="A":
                    fl=1
                    break
                if j=="X":
                    fl=2
                    break
                if j=="O":
                    fl=3
                    break
        if fl==0:
            d.append([nam[s[0]],s[1]])
        elif fl==1:
            d.append([i]+[nam[z] for z in s[1].split(" AND ")])
        elif fl==2:
            d.append([i]+[nam[z] for z in s[1].split(" XOR ")])
        else:
            d.append([i]+[nam[z] for z in s[1].split(" OR ")])
        nm[i]=fl

    mn=[False]*k
    mx=[False]*k
    for i in range(k):
        r1=0
        r2=0
        for ololo in range(n):
            eq=d[ololo]
            #print(bt1,bt2)
            if nm[ololo]==0:
                bt1[eq[0]]=bool(int(eq[1][i]))
                r1+=int(eq[1][i])
                bt2[eq[0]]=bool(int(eq[1][i]))
                r2+=int(eq[1][i])
                #print(int(bool(eq[1][i])))
            elif nm[ololo]==1:
                if bt1[eq[1]]==bt1[eq[2]]==True:
                    bt1[eq[0]]=True
                    r1+=1
                else:
                    bt1[eq[0]]=False
                if bt2[eq[1]]==bt2[eq[2]]==True:
                    bt2[eq[0]]=True
                    r2+=1
                else:
                    bt2[eq[0]]=False
            elif nm[ololo]==2:
                #print(bt1[eq[1]],eq,bt1[eq[2]])
                if bt1[eq[1]]!=bt1[eq[2]]:
                    bt1[eq[0]]=True
                    r1+=1
                else:
                    bt1[eq[0]]=False
                #print("wev",int(bt1[eq[0]]))
                if bt2[eq[1]]!=bt2[eq[2]]:
                    bt2[eq[0]]=True
                    r2+=1
                else:
                    bt2[eq[0]]=False
                #print('wfeaerhbjds',int(bt2[eq[0]]))
            else:
                if bt1[eq[1]]!=bt1[eq[2]] or bt1[eq[2]]!=False:
                    bt1[eq[0]]=True
                    r1+=1
                else:
                    bt1[eq[0]]=False
                if bt2[eq[1]]!=bt2[eq[2]] or bt2[eq[2]]!=False:
                    bt2[eq[0]]=True
                    r2+=1
                else:
                    bt2[eq[0]]=False
        #print(r1,r2,mn,mx)
        if r2>r1:
            mn[i]=True
        elif r2<r1:
            mx[i]=True

    stdout.write(''.join( (str(int(z)) for z in mx) ) + '\n')
    stdout.write(''.join( (str(int(z)) for z in mn) ) + '\n')

main()
```


802_E. Marmots (medium)

Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations.

Can you help Heidi estimate each village's population?

Input

Same as the easy version.

Output

Output one line per village, in the same order as provided in the input, containing your (integer) population estimate.

Your answer is considered correct if it is an integer that falls into the interval <image>, where P is the real population of the village, used to create the distribution (either Poisson or uniform) from which the marmots drew their answers.

```python
def sampleVariance(V):
    X = sum(V) / len(V)
    S = 0.0
    for x in V:
        S += (X-x)**2

    S /= (len(V)-1)
    return (X, S)

#That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester
for i in range(int(input())):
    V = list(map(int, input().split()))
    X, S = sampleVariance(V)
    v1 = X
    v2 = (2*X) ** 2 / 12

    if abs(v1-S) < abs(v2-S):
        print(int(X))
    else:
        print((max(V)+min(V)) // 2)
```


825_A. Binary Protocol

Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm:

  * Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones).
  * Digits are written one by one in order corresponding to number and separated by single '0' character.

Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.

Input

The first line contains one integer number n (1 ≤ n ≤ 89) — length of the string s.

The second line contains string s — sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 109. The string always starts with '1'.

Output

Print the decoded number.

Examples

Input

3
111

Output

3

Input

9
110011101

Output

2031

```python
x = int(input())
a = input()
l = 0
c = []
v = ''
b = a.split("0")
for i in b:
    g = len(i)
    c.append(g)
for p in c:
    v += str(p)
print(v)

```


847_L. Berland SU Computer Network

In the computer network of the Berland State University there are n routers numbered from 1 to n. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through other routers) is possible. There are no cycles in the network, so there is only one path between each pair of routers over patch cords.

Unfortunately, the exact topology of the network was lost by administrators. In order to restore it, the following auxiliary information was collected.

For each patch cord p, directly connected to the router i, list of routers located behind the patch cord p relatively i is known. In other words, all routers path from which to the router i goes through p are known. So for each router i there are ki lists, where ki is the number of patch cords connected to i.

For example, let the network consists of three routers connected in chain 1 - 2 - 3. Then:

  * the router 1: for the single patch cord connected to the first router there is a single list containing two routers: 2 and 3;
  * the router 2: for each of the patch cords connected to the second router there is a list: one list contains the router 1 and the other — the router 3;
  * the router 3: for the single patch cord connected to the third router there is a single list containing two routers: 1 and 2.

Your task is to help administrators to restore the network topology, i. e. to identify all pairs of routers directly connected by a patch cord.

Input

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of routers in the network.

The i-th of the following n lines contains a description of the lists for the router i.

The description of each list begins with the number of routers in it. Then the symbol ':' follows, and after that the numbers of routers from the list are given. This numbers are separated by comma. Lists are separated by symbol '-'.

It is guaranteed, that for each router i the total number of routers in its lists equals to n - 1 and all the numbers in lists of each router are distinct. For each router i lists do not contain the number i.

Output

Print -1 if no solution exists.

In the other case print to the first line n - 1 — the total number of patch cords in the network. In each of the following n - 1 lines print two integers — the routers which are directly connected by a patch cord. Information about each patch cord must be printed exactly once.

Patch cords and routers can be printed in arbitrary order.

Examples

Input

3
2:3,2
1:1-1:3
2:1,2

Output

2
2 1
2 3

Input

5
4:2,5,3,4
1:4-1:1-2:5,3
4:4,5,2,1
4:2,1,3,5
1:3-3:4,2,1

Output

4
2 1
2 4
5 2
3 5

Input

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

Output

-1

Note

The first example is analyzed in the statement.

The answer to the second example is shown on the picture.

<image>

The first router has one list, which contains all other routers. The second router has three lists: the first — the single router 4, the second — the single router 1, the third — two routers 3 and 5. The third router has one list, which contains all other routers. The fourth router also has one list, which contains all other routers. The fifth router has two lists: the first — the single router 3, the second — three routers 1, 2 and 4.

```python
import math
import sys
read = sys.stdin.readline
n = int(read())
sub = [[] for _ in range(n)]
for i in range(n):
    data = read().strip()
    for j in data.split('-'):
        tree = list(map(int, j.split(':')[1].split(',')))
        for k in range(len(tree)):
            tree[k] -= 1
        sub[i].append(sorted(tree))
    sub[i].sort()

dp = [[0] * n for _ in range(n)]
for i in range(n):
    for j in sub[i]:
        for k in j:
            dp[i][k] = n - len(j)

g = [[] for _ in range(n)]
for i in range(n):
    for j in range(n):
        if i < j and dp[i][j] + dp[j][i] == n:
            g[i].append(j)
            g[j].append(i)

def dfs(x, vis):
    arr = [x]
    vis[x] = True
    pt = 0
    while pt < len(arr):
        y = arr[pt]
        pt += 1
        for i in g[y]:
            if not vis[i]:
                vis[i] = True
                arr.append(i)
    return sorted(arr)

for i in range(n):
    subtree = []
    vis = [False] * n
    vis[i] = True
    for j in g[i]:
        arr = dfs(j, vis)
        subtree.append(arr)
    subtree.sort()
    if subtree != sub[i]:
        print(-1)
        sys.exit(0)

print(n - 1)
for i in range(n):
    for j in g[i]:
        if i < j:
            print(i + 1, j + 1)

```


896_A. Nephren gives a riddle

What are you doing at the end of the world? Are you busy? Will you save us?

<image>

Nephren is playing a game with little leprechauns.

She gives them an infinite array of strings, f0... ∞.

f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".

She wants to let more people know about it, so she defines fi =  "What are you doing while sending "fi - 1"? Are you busy? Will you send "fi - 1"?" for all i ≥ 1.

For example, f1 is

"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f1.

It can be seen that the characters in fi are letters, question marks, (possibly) quotation marks and spaces.

Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of fn. The characters are indexed starting from 1. If fn consists of less than k characters, output '.' (without quotes).

Can you answer her queries?

Input

The first line contains one integer q (1 ≤ q ≤ 10) — the number of Nephren's questions.

Each of the next q lines describes Nephren's question and contains two integers n and k (0 ≤ n ≤ 105, 1 ≤ k ≤ 1018).

Output

One line containing q characters. The i-th character in it should be the answer for the i-th query.

Examples

Input

3
1 1
1 2
1 111111111111

Output

Wh.

Input

5
0 69
1 194
1 139
0 47
1 66

Output

abdef

Input

10
4 1825
3 75
3 530
4 1829
4 1651
3 187
4 584
4 255
4 774
2 474

Output

Areyoubusy

Note

For the first two examples, refer to f0 and f1 given in the legend.

```python
f0 = 'What are you doing at the end of the world? Are you busy? Will you save us?'
ft1, ft2, ft3 = 'What are you doing while sending "', '"? Are you busy? Will you send "', '"?'

flen = [2 * 10 ** 18] * (10 ** 5 + 1)
flen[0] = len(f0)
for i in range(1, 56):
    flen[i] = len(ft1) + len(ft2) + len(ft3) + 2 * flen[i-1]

def ans(n, k):
    while True:
        if n == 0:
            return f0[k]
        if k < len(ft1):
            return ft1[k]
        k -= len(ft1)
        if k < flen[n-1]:
            n -= 1
            continue
        k -= flen[n-1]
        if k < len(ft2):
            return ft2[k]
        k -= len(ft2)
        if k < flen[n-1]:
            n -= 1
            continue
        k -= flen[n-1]
        return ft3[k]

q = int(input())
a = ''
for _ in range(q):
    n, k = map(int, input().split())
    k -= 1
    if k >= flen[n]:
        a += '.'
        continue
    a += ans(n, k)
print(a)

```


917_B. MADMAX

As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.

<image>

Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.

Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?

You have to determine the winner of the game for all initial positions of the marbles.

Input

The first line of input contains two integers n and m (2 ≤ n ≤ 100, <image>).

The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.

Output

Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.

Examples

Input

4 4
1 2 b
1 3 a
2 4 c
3 4 b

Output

BAAA
ABAA
BBBA
BBBB

Input

5 8
5 3 h
1 2 c
3 1 c
3 2 r
5 1 r
4 3 z
5 4 r
5 2 h

Output

BABBB
BBBBB
AABBB
AAABA
AAAAB

Note

Here's the graph in the first sample test case:

<image>

Here's the graph in the second sample test case:

<image>

```python
def mat(shape, inital_val=None):
    if len(shape) > 1:
        return [mat(shape[1:], inital_val) for _ in range(shape[0])]
    else:
        return [inital_val] * shape[0]

def main():
    n, m = [int(x) for x in input().split()]
    graph = [{} for _ in range(n)]
    for _ in range(m):
        v, u, c = input().split()
        graph[int(v) - 1][int(u) - 1] = c

    winner_table = mat([n, n, 26])

    def get_winner(u, v, char_to_beat):
        """
        Args:
            u: The position of current turn's player.
            v: The position of next turn's player.
            char_to_beat: The character played in the previous round.
        Returns:
            'A' if current turn's player wins, 'B' otherwise.
        """
        char_idx = ord(char_to_beat) - ord('a')
        if not winner_table[u][v][char_idx]:
            winner = 'B'
            for w, c in graph[u].items():
                if c >= char_to_beat and get_winner(v, w, c) == 'B':
                    winner = 'A'
                    break
            winner_table[u][v][char_idx] = winner
        return winner_table[u][v][char_idx]

    for i in range(n):
        print(''.join(get_winner(i, j, 'a') for j in range(n)))

if __name__ == '__main__':
    main()

```


93_B. End of Exams

Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams!

Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles — one bottle of each kind. We know that the volume of milk in each bottle equals w.

When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it?

Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!

Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.

Input

The only input data file contains three integers n, w and m (1 ≤ n ≤ 50, 100 ≤ w ≤ 1000, 2 ≤ m ≤ 50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company.

Output

Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO".

If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (v > 0) units of milk were poured into the i-th cup from bottle b (1 ≤ b ≤ n). All numbers b on each line should be different.

If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.

Examples

Input

2 500 3

Output

YES
1 333.333333
2 333.333333
2 166.666667 1 166.666667

Input

4 100 5

Output

YES
3 20.000000 4 60.000000
1 80.000000
4 40.000000 2 40.000000
3 80.000000
2 60.000000 1 20.000000

Input

4 100 7

Output

NO

Input

5 500 2

Output

YES
4 250.000000 5 500.000000 2 500.000000
3 500.000000 1 500.000000 4 250.000000

```python
import sys
from array import array  # noqa: F401

def input():
    return sys.stdin.buffer.readline().decode('utf-8')

n, w, m = map(int, input().split())
w = float(w)
eps = 1e-9
req = n * w / m
cup = [req] * m
ans = [[] for _ in range(m)]
j = 0

for i in range(n):
    milk = w
    cnt = 0
    while j < m and milk > eps:
        x = min(milk, cup[j])
        milk -= x
        cup[j] -= x
        ans[j].append(f'{i+1} {x:.8f}')
        cnt += 1
        if cup[j] < eps:
            j += 1
    if cnt > 2:
        print('NO')
        exit()

print('YES')
print('\n'.join(' '.join(line) for line in ans))

```


p02626 AtCoder Beginner Contest 172 - Unfair Nim

There are N piles of stones. The i-th pile has A_i stones.

Aoki and Takahashi are about to use them to play the following game:

* Starting with Aoki, the two players alternately do the following operation:
* Operation: Choose one pile of stones, and remove one or more stones from it.
* When a player is unable to do the operation, he loses, and the other player wins.

When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.

In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most (A_1 - 1) stones from the 1-st pile to the 2-nd pile before the game begins.

If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print `-1` instead.

Constraints

* 2 \leq N \leq 300
* 1 \leq A_i \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print `-1` instead.

Examples

Input

2
5 3

Output

1

Input

2
3 5

Output

-1

Input

3
1 1 2

Output

-1

Input

8
10 9 8 7 6 5 4 3

Output

3

Input

3
4294967297 8589934593 12884901890

Output

1

```python
import sys
from functools import lru_cache

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N, *A = map(int, read().split())

a, b = A[:2]
xor = 0
for x in A[2:]:
    xor ^= x

INF = 10**13

@lru_cache(None)
def F(a, b, xor):
    if (a & 1) ^ (b & 1) != (xor & 1):
        return INF
    if xor == 0:
        return INF if a < b else (a - b) // 2
    # 1の位を放置
    x = 2 * F(a // 2, b // 2, xor // 2)
    # 1の位を移動
    y = 2 * F((a - 1) // 2, (b + 1) // 2, xor // 2) + 1
    x = min(x, y)
    if x >= INF:
        x = INF
    return x

x = F(a, b, xor)
if x >= a:
    x = -1
print(x)
```


p02757 AtCoder Beginner Contest 158 - Divisible Substring

Takahashi has a string S of length N consisting of digits from `0` through `9`.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a `0` also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

* 1 \leq N \leq 2 \times 10^5
* S consists of digits.
* |S| = N
* 2 \leq P \leq 10000
* P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Examples

Input

4 3
3543

Output

6

Input

4 2
2020

Output

10

Input

20 11
33883322005544116655

Output

68

```python
n,m=map(int,input().split());s=input();l=[0]*m;a,t,p=0,0,1
if 10%m:
  for i in s[::-1]:l[t%m]+=1;t+=int(i)*p;a+=l[t%m];p=p*10%m
else:a=sum(i+1 for i in range(n) if int(s[i])%m<1)
print(a)
```


p02892 AtCoder Grand Contest 039 - Graph Partition

Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge.

Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division.

* Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds.

Constraints

* 2 \leq N \leq 200
* S_{i,j} is `0` or `1`.
* S_{i,i} is `0`.
* S_{i,j}=S_{j,i}
* The given graph is connected.
* N is an integer.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}...S_{1,N}
:
S_{N,1}...S_{N,N}

Output

If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1. Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition.

Examples

Input

2
01
10

Output

2

Input

3
011
101
110

Output

-1

Input

6
010110
101001
010100
101000
100000
010000

Output

4

```python
from collections import deque
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline

n = int(input())
edge = [[] for _ in range(n)]
mat = [[1000] * n for _ in range(n)]
for i in range(n):
    s = input().rstrip()
    for j, ch in enumerate(s):
        if ch == "1":
            mat[i][j] = 1
            if j > i:
                edge[i].append(j)
                edge[j].append(i)
for i in range(n):
    mat[i][i] = 0
for k in range(n):
    for i in range(n):
        for j in range(n):
            mat[i][j] = min(mat[i][j], mat[i][k] + mat[k][j])

ans = 0
dq = deque()
dist = [-1] * n
dq.append((0, 0))
ok = True
while dq:
    v, d = dq.popleft()
    if dist[v] == d:
        continue
    if dist[v] == -1:
        dist[v] = d
    else:
        ok = False
        break
    for item in edge[v]:
        if dist[item] == -1:
            dq.append((item, d+1))

if ok:
    ans = 0
    for line in mat:
        ans = max(ans, max(line))
    print(ans + 1)
else:
    print(-1)
```


p03027 M-SOLUTIONS Programming Contest - Product of Arithmetic Progression

Consider the following arithmetic progression with n terms:

* x, x + d, x + 2d, \ldots, x + (n-1)d

What is the product of all terms in this sequence? Compute the answer modulo 1\ 000\ 003.

You are given Q queries of this form. In the i-th query, compute the answer in case x = x_i, d = d_i, n = n_i.

Constraints

* 1 \leq Q \leq 10^5
* 0 \leq x_i, d_i \leq 1\ 000\ 002
* 1 \leq n_i \leq 10^9
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
x_1 d_1 n_1
:
x_Q d_Q n_Q

Output

Print Q lines.

In the i-th line, print the answer for the i-th query.

Example

Input

2
7 2 4
12345 67890 2019

Output

9009
916936


p03168 Educational DP Contest - Coins

Let N be a positive odd number.

There are N coins, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i.

Taro has tossed all the N coins. Find the probability of having more heads than tails.

Constraints

* N is an odd number.
* 1 \leq N \leq 2999
* p_i is a real number and has two decimal places.
* 0 < p_i < 1

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 \ldots p_N

Output

Print the probability of having more heads than tails. The output is considered correct when the absolute error is not greater than 10^{-9}.

Examples

Input

3
0.30 0.60 0.80

Output

0.612

Input

1
0.50

Output

0.5

Input

5
0.42 0.01 0.42 0.99 0.42

Output

0.3821815872

```python
n=int(input())
p=list(map(float,input().split()))
dp=[[0 for _ in range(n+1)]for _ in range(n)]
dp[0][0]=1-p[0]
dp[0][1]=p[0]
for i in range(1,n):
  for j in range(i+2):
    dp[i][j]=dp[i-1][j-1]*p[i]+dp[i-1][j]*(1-p[i])
print(sum(dp[-1][(n+1)//2:]))
```


p03313 AtCoder Regular Contest 100 - Or Plus Max

There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.)

For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem:

* Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K. Here, or denotes the bitwise OR.

Constraints

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

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 ... A_{2^N-1}

Output

Print 2^N-1 lines. In the i-th line, print the answer of the problem above for K=i.

Examples

Input

2
1 2 3 1

Output

3
4
5

Input

3
10 71 84 33 6 47 23 25

Output

81
94
155
155
155
155
155

Input

4
75 26 45 72 81 47 97 97 2 2 25 82 84 17 56 32

Output

101
120
147
156
156
178
194
194
194
194
194
194
194
194
194

```python
n = int(input())
aaa = list(map(int, input().split()))
n2 = 1 << n
dp = [[a, 0] for a in aaa]

for j in range(n):
    b = 1 << j
    for i in range(n2):
        if not i & b:
            dpi, dpk = dp[i], dp[i | b]
            if dpk[0] < dpi[0]:
                dpk[1] = max(dpk[0], dpi[1])
                dpk[0] = dpi[0]
            elif dpk[1] < dpi[0]:
                dpk[1] = dpi[0]

ans = []
tmp = 0
for a in dp[1:]:
    tmp = max(tmp, a[0] + a[1])
    ans.append(tmp)
print(*ans)

```


p03470 AtCoder Beginner Contest 085 - Kagami Mochi

An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have a 3-layered kagami mochi; if you put just one mochi, you have a 1-layered kagami mochi.

Lunlun the dachshund has N round mochi, and the diameter of the i-th mochi is d_i centimeters. When we make a kagami mochi using some or all of them, at most how many layers can our kagami mochi have?

Constraints

* 1 ≤ N ≤ 100
* 1 ≤ d_i ≤ 100
* All input values are integers.

Input

Input is given from Standard Input in the following format:

N
d_1
:
d_N

Output

Print the maximum number of layers in a kagami mochi that can be made.

Examples

Input

4
10
8
8
6

Output

3

Input

3
15
15
15

Output

1

Input

7
50
30
50
100
50
80
30

Output

4


p03632 AtCoder Beginner Contest 070 - Two Switches

Alice and Bob are controlling a robot. They each have one switch that controls the robot.
Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.
Bob started holding down his button C second after the start-up, and released his button D second after the start-up.
For how many seconds both Alice and Bob were holding down their buttons?

Constraints

* 0≤A<B≤100
* 0≤C<D≤100
* All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Examples

Input

0 75 25 100

Output

50

Input

0 33 66 99

Output

0

Input

10 90 20 80

Output

60

```python
a,b,c,d=map(int,input().split())
print(max(0,min(d,b)-max(a,c)))
```


p03790 AtCoder Grand Contest 011 - Train Service Planning

There is a railroad in Takahashi Kingdom. The railroad consists of N sections, numbered 1, 2, ..., N, and N+1 stations, numbered 0, 1, ..., N. Section i directly connects the stations i-1 and i. A train takes exactly A_i minutes to run through section i, regardless of direction. Each of the N sections is either single-tracked over the whole length, or double-tracked over the whole length. If B_i = 1, section i is single-tracked; if B_i = 2, section i is double-tracked. Two trains running in opposite directions can cross each other on a double-tracked section, but not on a single-tracked section. Trains can also cross each other at a station.

Snuke is creating the timetable for this railroad. In this timetable, the trains on the railroad run every K minutes, as shown in the following figure. Here, bold lines represent the positions of trains running on the railroad. (See Sample 1 for clarification.)

<image>

When creating such a timetable, find the minimum sum of the amount of time required for a train to depart station 0 and reach station N, and the amount of time required for a train to depart station N and reach station 0. It can be proved that, if there exists a timetable satisfying the conditions in this problem, this minimum sum is always an integer.

Formally, the times at which trains arrive and depart must satisfy the following:

* Each train either departs station 0 and is bound for station N, or departs station N and is bound for station 0.
* Each train takes exactly A_i minutes to run through section i. For example, if a train bound for station N departs station i-1 at time t, the train arrives at station i exactly at time t+A_i.
* Assume that a train bound for station N arrives at a station at time s, and departs the station at time t. Then, the next train bound for station N arrives at the station at time s+K, and departs the station at time t+K. Additionally, the previous train bound for station N arrives at the station at time s-K, and departs the station at time t-K. This must also be true for trains bound for station 0.
* Trains running in opposite directions must not be running on the same single-tracked section (except the stations at both ends) at the same time.

Constraints

* 1 \leq N \leq 100000
* 1 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* A_i is an integer.
* B_i is either 1 or 2.

Input

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

N K
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print an integer representing the minimum sum of the amount of time required for a train to depart station 0 and reach station N, and the amount of time required for a train to depart station N and reach station 0. If it is impossible to create a timetable satisfying the conditions, print -1 instead.

Examples

Input

3 10
4 1
3 1
4 1

Output

26

Input

1 10
10 1

Output

-1

Input

6 4
1 1
1 1
1 1
1 1
1 1
1 1

Output

12

Input

20 987654321
129662684 2
162021979 1
458437539 1
319670097 2
202863355 1
112218745 1
348732033 1
323036578 1
382398703 1
55854389 1
283445191 1
151300613 1
693338042 2
191178308 2
386707193 1
204580036 1
335134457 1
122253639 1
824646518 2
902554792 2

Output

14829091348

```python
import sys

def merge_delay_pattern(k, half1, half2):
    len1 = len(half1)
    len2 = len(half2)

    start, delay1_next = half1[0]
    start2 = half2[0][0]
    time1 = start - start2
    mid_start = start + time1 + delay1_next
    offset2_num_period = (mid_start - start2) // k
    offset2_phase = mid_start - offset2_num_period * k
    for head2 in range(len2):
        if half2[head2][0] >= offset2_phase:
            head2 -= 1
            break
    head2 += offset2_num_period * len2
    head1 = 0

    ret = []
    prev = ()
    half1.append((start + k, None))

    pos1_next = start
    pos2_next, delay2_next = half2[head2 % len2]
    pos2_next += (head2 // len2) * k
    mid = pos2_next
    while True:
        if mid <= pos2_next:
            if head1 == len1: break
            head1 += 1
            pos1, delay1 = pos1_next, delay1_next
            pos1_next, delay1_next = half1[head1]
        if pos2_next <= mid:
            head2 += 1
            pos2, delay2 = pos2_next, delay2_next
            pos2_next, delay2_next = half2[head2 % len2]
            pos2_next += (head2 // len2) * k
        if delay1 == 0:
            mid = pos1_next + time1
            if delay2 == 0:
                if prev is not None:
                    ret.append((start, 0))
                    prev = None
            else:
                delay = pos2 + delay2 - time1 - start
                if prev != start + delay:
                    ret.append((start, delay))
                    prev = start + delay
            if pos2_next <= mid:
                start = pos2_next - time1
            else:
                start = pos1_next
        else:
            mid = pos1 + time1 + delay1
            if mid <= pos2_next:
                if delay2 == 0:
                    delay = delay1
                else:
                    delay = pos2 + delay2 - time1 - start
                if prev != start + delay:
                    ret.append((start, delay))
                    prev = start + delay
                start = pos1_next
    return ret

def get_delay_pattern(k, data, first, last):
    if last - first == 1: return data[first]
    middle = (first + last) // 2
    half1 = get_delay_pattern(k, data, first, middle)
    half2 = get_delay_pattern(k, data, middle, last)
    return merge_delay_pattern(k, half1, half2)

def solve():
    data = []
    int_list = [int(s) for s in sys.stdin.read().split()]

    n = int_list[0]
    k = int_list[1]

    position = 0
    for i in range(2, (n + 1) * 2, 2):
        a = int_list[i]
        b = int_list[i + 1]
        if b == 1:
            a2 = a * 2
            if k < a2: return -1
            data.append([(-position, 0), (-position + k - a2, a2)])
        position += a

    if not data: return position * 2
    delay_pattern = get_delay_pattern(k, data, 0, len(data))
    pat_adj_pairs = zip(delay_pattern, delay_pattern[1:] + [(delay_pattern[0][0] + k, None)])
    delay_list = (pos + delay - next_pos for (pos, delay), (next_pos, _) in pat_adj_pairs if delay)
    return position * 2 + min(delay_list, default=0)

print(solve())

```


p03958 CODE FESTIVAL 2016 qual C - K Cakes

There are K pieces of cakes. Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun, so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

* 1 ≤ K ≤ 10000
* 1 ≤ T ≤ 100
* 1 ≤ a_i ≤ 100
* a_1 + a_2 + ... + a_T = K

Input

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

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Examples

Input

7 3
3 2 2

Output

0

Input

6 3
1 4 1

Output

1

Input

100 1
100

Output

99

```python
#!/usr/bin/env python3
k,t = map(int,input().split())
a = list(map(int,input().split()))
print(max(0,2*(max(a)-(k+1)//2)-1))
```


p00050 Apple and Peach

Fukushima Prefecture is also famous for producing fruits, and among them, peaches and apples boast one of the highest production volumes in Japan. By the way, when I made a print manuscript of an English pamphlet for sale, I mistakenly wrote the description about apples and the description about peaches in reverse.

You've been tasked with fixing apple and peach, but it's kind of annoying. Enter a single line of English text and create a program that outputs the English text with all the character strings apple in it replaced with peach and all the character strings peach replaced with apple.

Input

English text (including half-width alphanumeric characters, spaces, and symbols) is given on one line. The length of the string entered is 1000 or less.

Output

Outputs English sentences with the character strings apple and peach exchanged on one line.

Example

Input

the cost of one peach is higher than that of one apple.

Output

the cost of one apple is higher than that of one peach.

```python
a,p,t='apple','peach','_'
print(input().replace(a,t).replace(p,a).replace(t,p))

```


p00180 Demolition of Bridges

Water Country Water Deven has n cities. Each city is surrounded by water and looks like an island country. Water Deven has m bridges, and transportation between cities is carried out by these bridges, which allows you to travel to and from all cities.

Recently, it was decided to reduce the maintenance cost of the bridge by reviewing the road specific financial resources. I couldn't maintain all the bridges and had to demolish some of them. Therefore, the challenge for Water Deven was to minimize the cost of maintaining the bridge while leaving the bridge so that it could reach any city.

Create a program that inputs the number of cities, the number of bridges, and the maintenance cost of each bridge, so that you can go to any city using the bridge, and outputs the minimum value of the maintenance cost when the bridge is demolished. Please give me. There is no cost to demolish the bridge. However, each city shall be numbered sequentially from 0 to n-1.

Input

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

n m
a1 b1 cost1
a2 b2 cost2
::
am bm costm

The first line gives the number of cities n (2 ≤ n ≤ 100) and the number of bridges m (1 ≤ m ≤ 500). The following m lines give information about the i-th bridge. ai and bi are the numbers of the cities to which the bridge is connected, and costi (1 ≤ costi ≤ 1000) is the maintenance cost of the bridge.

Output

The total bridge maintenance cost is output to one line for each data set.

Example

Input

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

Output

10
6

```python

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * (n+1)

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n+1) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def kr(edge,N):
    res = 0
    node = []
    G = UnionFind(N)
    for cost, p, q, in edge:
        if not G.same(p, q):
            G.union(p, q)
            res += cost
    return res

def solve():
    n,m=map(int,input().split())
    if n==0 and m==0:
        exit()
    edge=[]
    for _ in range(m):
        a,b,cost=map(int,input().split())
        edge.append((cost,a,b))
    edge.sort()
    ans=kr(edge,n)
    print(ans)
    return solve()
if __name__=="__main__":
  solve()

```


p00336 Repeated Spell

We, the researchers who discovered and investigated the ancient nation Iwashiro, finally discovered the temple in the center of Iwashiro. A lithograph dedicated to the god of Iwashiro was stored in the temple. On the lithograph, two strings were written, one for each sentence and one for the spell.

In Iwashiro, how many times a spell appears in a sentence has an important meaning. However, it is considered that all the characters contained in the spell appear in order, and some of them appear in the sentence in a discrete manner once. For example, if the sentence is "abab" and the spell is "ab", then "ab" appears three times in "abab", including non-continuous ones (three ways: abab, abab, and abab).

Create a program that prints how many times a spell appears in a sentence when it is given a sentence and a spell.

Input

The input is given in the following format.

t
b b

The first line is given the string t that represents the text written on the lithograph. The second line is given the string b that represents the spell written on the lithograph. Both strings are composed of only lowercase letters and have a length of 1 or more and 1000 or less.

Output

Prints how many times a spell appears in a sentence on one line. However, the value to be output can be very large, so instead output the remainder divided by 1,000,000,007.

Examples

Input

abab
ab

Output

3

Input

aaaabaaaabaaaabaaaab
aaaaa

Output

4368

Input

data
structure

Output

0

```python
t = input()
b = input()

MOD = 10**9 + 7

cnts = [0]*(len(b)+1)
cnts[0] = 1

for c in t:
    for i in range(len(b)-1, -1, -1):
        if c == b[i]:
            cnts[i+1] = (cnts[i+1] + cnts[i]) % MOD
print(cnts[-1])
```


p00527 Take the 'IOI' train

Take the'IOI'train

A new railway has been laid in IOI. Trains running on railways in IOI are a combination of several vehicles, and there are two types of vehicles, I and O. Vehicles can only be connected to different types of vehicles. Also, because the train has a driver's seat, the cars at both ends of the train must be of type I. A train is represented by a character string in which characters indicating the type of vehicle are connected in order, and the length of the train is assumed to be the length of the character string. For example, if vehicles are connected in the order of IOIOI, a train with a length of 5 can be formed, and vehicle I is a train with a length of 1 alone. Trains cannot be formed by arranging vehicles in the order of OIOI or IOOI.

Some vehicles are stored in two garages. Vehicles are lined up in a row in each garage. When forming a train, take out the train from the garage and connect it in front of the garage. Only the vehicle closest to the entrance of the garage can be taken out of the garage, but the order of taking out the vehicle from which garage is arbitrary.

Before forming a train, you can take as many cars out of the garage as you like and move them to another waiting rail. Vehicles that have been moved to the standby rails cannot be used to organize trains in the future. Also, once the train formation is started, the vehicle cannot be moved from the garage to the standby rail until the formation is completed.

When organizing a train, it is not necessary to use up all the cars in the garage. That is, after the train formation is completed, unused cars may remain in the garage.

It is believed that there are so many people on the railroad in IOI, so I want to organize the longest possible train.

<image>

Figure: The train is being organized, and the vehicle in the garage cannot be moved to the standby rail at this time. This figure corresponds to I / O example 1.

Task

Create a program to find the maximum length of trains that can be organized given the information of the cars stored in the garage. The row of vehicles stored in each garage is represented by a string consisting of only two types of letters I and O, and the information in the two garages is represented by the string S of length M and the string T of length N, respectively. Given. Each letter represents one vehicle, the letter of which is the same as the type of vehicle. The first letter of the string represents the vehicle closest to the entrance to the garage, and the last letter represents the vehicle closest to the garage.

Limits

* 1 ≤ M ≤ 2000 Length of string S
* 1 ≤ N ≤ 2000 Length of string T

input

Read the following data from standard input.

* In the first line, M and N are written separated by blanks.
* The character string S is written on the second line.
* The character string T is written on the third line.

output

Output an integer representing the maximum train length that can be organized to the standard output on one line. If no train can be organized, output 0.

Input / output example

Input example 1

5 5
OIOOI
OOIOI

Output example 1

7

Let the garage represented by S be the garage S and the garage represented by T be the garage T. At this time, for example, the first vehicle from the garage S, the first two vehicles from the garage T are put out and put on standby, and then the garage S, the garage S, the garage T, the garage S, the garage S, the garage T, and the garage T are placed in this order. If you take out the vehicle, you can form a train IOIOIOI with a length of 7.

In addition, after the first vehicle from garage S and the first two vehicles from garage T are put out and put on standby, the order is garage T, garage T, garage S, garage S, garage T, garage S, and garage S. You can also organize a 7-length train by putting out a vehicle. Since it is not possible to form a train longer than this, 7 is output.

Input example 2

5 9
IIIII
IIIIIIIII

Output example 2

1

Note that train I, which consists of only one car, also meets the conditions for a train.

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

Example

Input

5 5
OIOOI
OOIOI

Output

7

```python
def main():
    M, N = map(int, input().split())
    S = input()
    T = input()

    INF = 10**18

    dp0 = [[0]*(N+1) for i in range(M+1)]
    dp1 = [[-INF]*(N+1) for i in range(M+1)]
    for p in range(M+1):
        for q in range(N+1):
            v0 = dp0[p][q]
            v1 = dp1[p][q]

            if p < M:
                if S[p] == 'I':
                    dp1[p+1][q] = max(dp1[p+1][q], v0+1)
                else:
                    dp0[p+1][q] = max(dp0[p+1][q], v1+1)
            if q < N:
                if T[q] == 'I':
                    dp1[p][q+1] = max(dp1[p][q+1], v0+1)
                else:
                    dp0[p][q+1] = max(dp0[p][q+1], v1+1)

    ans = max(max(e) for e in dp1)
    print(max(ans, 0))
main()

```


p00694 Strange Key

Professor Tsukuba invented a mysterious jewelry box that can be opened with a special gold key whose shape is very strange. It is composed of gold bars joined at their ends. Each gold bar has the same length and is placed parallel to one of the three orthogonal axes in a three dimensional space, i.e., x-axis, y-axis and z-axis.

The locking mechanism of the jewelry box is truly mysterious, but the shape of the key is known. To identify the key of the jewelry box, he gave a way to describe its shape.

The description indicates a list of connected paths that completely defines the shape of the key: the gold bars of the key are arranged along the paths and joined at their ends. Except for the first path, each path must start from an end point of a gold bar on a previously defined path. Each path is represented by a sequence of elements, each of which is one of six symbols (+x, -x, +y, -y, +z and -z) or a positive integer. Each symbol indicates the direction from an end point to the other end point of a gold bar along the path. Since each gold bar is parallel to one of the three orthogonal axes, the 6 symbols are enough to indicate the direction. Note that a description of a path has direction but the gold bars themselves have no direction.

An end point of a gold bar can have a label, which is a positive integer. The labeled point may be referred to as the beginnings of other paths. In a key description, the first occurrence of a positive integer defines a label of a point and each subsequent occurrence of the same positive integer indicates the beginning of a new path at the point.

An example of a key composed of 13 gold bars is depicted in Figure 1.

<image>

The following sequence of lines

19
1 +x 1 +y +z 3 +z
3 +y -z +x +y -z -x +z 2 +z
2 +y

is a description of the key in Figure 1. Note that newlines have the same role as space characters in the description, so that `"19 1 +x 1 +y +z 3 +z 3 +y -z +x +y -z -x +z 2 +z 2 +y"` has the same meaning.

The meaning of this description is quite simple. The first integer "19" means the number of the following elements in this description. Each element is one of the 6 symbols or a positive integer.

The integer "1" at the head of the second line is a label attached to the starting point of the first path. Without loss of generality, it can be assumed that the starting point of the first path is the origin, i.e., (0,0,0), and that the length of each gold bar is 1. The next element "+x" indicates that the first gold bar is parallel to the x-axis, so that the other end point of the gold bar is at (1,0,0). These two elements "1" and "+x" indicates the first path consisting of only one gold bar. The third element of the second line in the description is the positive integer "1", meaning that the point with the label "1", i.e., the origin (0,0,0) is the beginning of a new path. The following elements "+y", "+z", "3", and "+z" indicate the second path consisting of three gold bars. Note that this "3" is its first occurrence so that the point with coordinates (0,1,1) is labeled "3". The head of the third line "3" indicates the beginning of the third path and so on. Consequently, there are four paths by which the shape of the key in Figure 1 is completely defined.

Note that there are various descriptions of the same key since there are various sets of paths that cover the shape of the key. For example, the following sequence of lines

19
1 +x 1 +y +z 3 +y -z +x +y -z -x +z 2 +y
3 +z
2 +z

is another description of the key in Figure 1, since the gold bars are placed in the same way.

Furthermore, the key may be turned 90-degrees around x-axis, y-axis or z-axis several times and may be moved parallelly. Since any combinations of rotations and parallel moves don't change the shape of the key, a description of a rotated and moved key also represent the same shape of the original key. For example, a sequence

17
+y 1 +y -z +x
1 +z +y +x +z +y -x -y 2 -y
2 +z

is a description of a key in Figure 2 that represents the same key as in Figure 1. Indeed, they are congruent under a rotation around x-axis and a parallel move.

<image>

Your job is to write a program to judge whether or not the given two descriptions define the same key.

Note that paths may make a cycle. For example, `"4 +x +y -x -y"` and `"6 1 +x 1 +y +x -y"` are valid descriptions. However, two or more gold bars must not be placed at the same position. For example, key descriptions `"2 +x -x"` and `"7 1 +x 1 +y +x -y -x"` are invalid.

Input

An input data is a list of pairs of key descriptions followed by a zero that indicates the end of the input. For p pairs of key descriptions, the input is given in the following format.

key-description1-a
key-description1-b
key-description2-a
key-description2-b
...
key-descriptionp-a
key-descriptionp-b
0

Each key description (key-description) has the following format.

n` ` e1 ` ` e2 ` ` ... ` ` ek ` ` ... ` ` en

The positive integer n indicates the number of the following elements e1, ..., en . They are separated by one or more space characters and/or newlines. Each element ek is one of the six symbols (`+x`, `-x`, `+y`, `-y`, `+z` and `-z`) or a positive integer.

You can assume that each label is a positive integer that is less than 51, the number of elements in a single key description is less than 301, and the number of characters in a line is less than 80. You can also assume that the given key descriptions are valid and contain at least one gold bar.

Output

The number of output lines should be equal to that of pairs of key descriptions given in the input. In each line, you should output one of two words "SAME", when the two key descriptions represent the same key, and "DIFFERENT", when they are different. Note that the letters should be in upper case.

Examples

Input

19
  1 +x 1 +y +z 3 +z
  3 +y -z +x +y -z -x +z 2 +z
  2 +y
19
  1 +x 1 +y +z 3 +y -z +x +y -z -x +z 2 +y
  3 +z
  2 +z
19
  1 +x 1 +y +z 3 +z
  3 +y -z +x +y -z -x +z 2 +y
  2 +z
18
  1 -y
  1 +y -z +x
  1 +z +y +x +z +y -x -y 2 -y
  2 +z
3 +x +y +z
3 +y +z -x
0

Output

SAME
SAME
DIFFERENT

Input

19
1 +x 1 +y +z 3 +z
3 +y -z +x +y -z -x +z 2 +z
2 +y
19
1 +x 1 +y +z 3 +y -z +x +y -z -x +z 2 +y
3 +z
2 +z
19
1 +x 1 +y +z 3 +z
3 +y -z +x +y -z -x +z 2 +y
2 +z
18
1 -y
1 +y -z +x
1 +z +y +x +z +y -x -y 2 -y
2 +z
3 +x +y +z
3 +y +z -x
0

Output

SAME
SAME
DIFFERENT

```python
def solve(sentence):
    now = [0, 0, 0]  # x,y,z
    num_p = {}
    positions = []
    for s in sentence:
        if s.isdecimal():
            if s in num_p:
                now = num_p[s]
            else:
                num_p[s] = now
        else:
            sign = 1 if s[0] == "+" else -1
            if s[1] == "x":
                positions.append([now.copy(), [now[0] + sign, now[1], now[2]]])
                now = [now[0] + sign, now[1], now[2]]
            if s[1] == "y":
                positions.append([now.copy(), [now[0], now[1] + sign, now[2]]])
                now = [now[0], now[1] + sign, now[2]]
            if s[1] == "z":
                positions.append([now.copy(), [now[0], now[1], now[2] + sign]])
                now = [now[0], now[1], now[2] + sign]
    return positions

def rotateX(positions):
    miny = float("inf")
    minz = float("inf")
    for i in range(len(positions)):
        for j in range(2):
            positions[i][j][1], positions[i][j][2] = -positions[i][j][2], positions[i][j][1]
            if positions[i][j][1] < miny:
                miny = positions[i][j][1]
            if positions[i][j][2] < minz:
                minz = positions[i][j][2]
    # シフト
    for i in range(len(positions)):
        for j in range(2):
            positions[i][j][1] -= miny
            positions[i][j][2] -= minz
        positions[i].sort()
    return positions

def rotateY(positions):
    minx = float("inf")
    minz = float("inf")
    for i in range(len(positions)):
        for j in range(2):
            positions[i][j][0], positions[i][j][2] = -positions[i][j][2], positions[i][j][0]
            if positions[i][j][0] < minx:
                minx = positions[i][j][0]
            if positions[i][j][2] < minz:
                minz = positions[i][j][2]
    # シフト
    for i in range(len(positions)):
        for j in range(2):
            positions[i][j][0] -= minx
            positions[i][j][2] -= minz
        positions[i].sort()
    return positions

def rotateZ(positions):
    minx = float("inf")
    miny = float("inf")
    for i in range(len(positions)):
        for j in range(2):
            positions[i][j][0], positions[i][j][1] = -positions[i][j][1], positions[i][j][0]
            if positions[i][j][0] < minx:
                minx = positions[i][j][0]
            if positions[i][j][1] < miny:
                miny = positions[i][j][1]
    # シフト
    for i in range(len(positions)):
        for j in range(2):
            positions[i][j][0] -= minx
            positions[i][j][1] -= miny
        positions[i].sort()
    return positions

def normal(positions):
    minx = float("inf")
    miny = float("inf")
    minz = float("inf")
    for i in range(len(positions)):
        if positions[i][0][0] < minx:
            minx = positions[i][0][0]
        if positions[i][1][0] < minx:
            minx = positions[i][1][0]

        if positions[i][0][1] < miny:
            miny = positions[i][0][1]
        if positions[i][1][1] < miny:
            miny = positions[i][1][1]

        if positions[i][0][2] < minz:
            minz = positions[i][0][2]
        if positions[i][1][2] < minz:
            minz = positions[i][1][2]

    for i in range(len(positions)):
        for j in range(2):
            positions[i][j][0] -= minx
            positions[i][j][1] -= miny
            positions[i][j][2] -= minz
        positions[i].sort()
    return positions

def check(position1, position2):
    if len(position1) != len(position2):
        return False

    position1.sort()
    position2.sort()
    for i in range(len(position1)):
        if position1[i][0] not in position2[i] or position1[i][1] not in position2[i]:
            return False
    return True

while True:
    string = input()
    if string != "":
        n, *S = string.split()
    else:
        continue
    n = int(n)
    if n == 0:
        break
    while len(S) < n:
        S += input().split()
    position1 = normal(solve(S))

    n, *S = input().split()
    n = int(n)
    while len(S) < n:
        S += input().split()
    position2 = normal(solve(S))

    # 入力ここまで

    end = False
    for z in range(4):
        for y in range(4):
            for x in range(4):
                if check(position1, position2):
                    end = True
                    break
                position2 = rotateX(position2)
            if end:
                break
            position2 = rotateY(position2)
        if end:
            break
        position2 = rotateZ(position2)

    if end:
        print("SAME")
    else:
        print("DIFFERENT")

```


p01398 Swap Cipher

Problem A: Swap crypto

A 2D enthusiast at R University, he often writes embarrassing sentences that blush when seen by people. Therefore, in order for a third party to not be able to see the text he is writing, he encrypts the text using a method called swap encryption that he devised independently. In swap encryption, the following steps are repeated N times to perform encryption.

1. Swap the ai and bi of the string
2. Return these two characters in alphabetical order by the difference between ai and bi

However, in alphabetical order, "z" is used before "a".

For example, if the character string "aojwo" is encrypted with a1 = 1 and b1 = 4, it will be as follows.

1. Swap the 1st and 4th ("aojwo" → "wojao")
2. Return these two letters'w'and'a' in alphabetical order by the difference between 1 and 4 = 3 ("wojao"-> "tojxo")
* If'w'is returned by 3 in alphabetical order, it becomes'w' →'v' →'u' →'t'.
* If'a'is returned by 3 in alphabetical order, it becomes'a' →'z' →'y' →'x'.

Therefore, "aojwo" is encrypted as "tojxo".

This encryption should have allowed him to encrypt his text without knowing the original text, but perhaps he leaked the swap operation process he used to encrypt it. Your job is to create a program that "decrypts" given the encrypted strings and the swap operation used for encryption, and dismisses him as a 2D enthusiast.

Input

The input consists of multiple datasets. The total number of datasets is 20 or less. Each dataset has the following format:

N
message
a1 b1
...
ai bi
...
aN bN

N (0 <N ≤ 100) is an integer that indicates the number of swap operations when encrypting. message indicates encrypted data. Cryptographic data is a character string consisting of only lowercase letters of the alphabet. If the length of the message is len, we can assume that 2 ≤ len ≤ 100.

ai and bi represent two indexes that have been swapped in encryption. You can assume that 1 ≤ ai <bi ≤ len. For encryption, it is assumed that the swap operations are performed in the order in which they are entered.

The end of the input is indicated by a single line consisting of only 0s. This data does not need to be processed.

Output

Output the decrypted string on one line for each dataset.

Sample Input

1
tojxo
14
Five
uhcqmlmkv
4 5
6 9
3 6
1 7
3 6
Five
shzxadexonr
8 9
3 9
5 8
4 9
10 11
0

Output for Sample Input

aojwo
shinryaku
shitadegeso

Example

Input

1
tojxo
1 4
5
uhcqmlmkv
4 5
6 9
3 6
1 7
3 6
5
shzxadexonr
8 9
3 9
5 8
4 9
10 11
0

Output

aojwo
shinryaku
shitadegeso

```python
while True:
  n = int(input())
  if n == 0:break
  mes = list(input())
  mes = [ord(c) - ord("a") for c in mes]
  ablst = [tuple(map(int, input().split())) for _ in range(n)]
  ablst.reverse()
  for a, b in ablst:
    a -= 1
    b -= 1
    mes[b], mes[a] = (mes[a] + (b - a)) % 26, (mes[b] + (b - a)) % 26
  mes = [chr(i + ord("a")) for i in mes]
  print("".join(mes))

```


p01551 DNA

A gene is a string consisting of `A`,` T`, `G`,` C`. The genes in this world are strangely known to obey certain syntactic rules.

Syntax rules are given in the following form:

Non-terminal symbol 1: Symbol 1_1 Symbol 1_2 ... Symbol 1_n1
Non-terminal symbol 2: Symbol 2_1 Symbol 2_2 ... Symbol 2_n2
...
Non-terminal symbol m: symbol m_1 symbol m_2 ... symbol m_nm

The symbol is either a nonterminal symbol or a terminal symbol. Non-terminal symbols are represented by lowercase strings, and terminal symbols are some of the characters `A`,` T`, `G`,` C` surrounded by "` [` "and" `]` ". It is represented by a character string.

An example syntax rule looks like this:

dna: a a b b
a: [AT]
b: [GC]

"` Nonterminal symbol i: Symbol i_1 Symbol i_2 ... Symbol i_ni` "is called a rule for nonterminal symbol i, and there is exactly one rule for each nonterminal symbol that appears in the syntax rule.

A string s "` matches `" with the nonterminal i means that there is a substring {sj} of s such that s = s1 + s2 + ... + sni, and sj (1 ≤ j ≤ It means that ni) matches the symbol j in the rule.

When the string s "` matches `" with a terminal symbol, it means that the string consists of one character and that character is included in the string representing the terminal symbol.

A string that follows syntax rules means that it matches nonterminal symbol 1.

Rule i does not include the nonterminal symbol j (j ≤ i) in the symbol.

Given the syntax rules and the four integers Na, Nt, Ng, Nc. According to the syntax rules, find the remainder of the total number of genes that contain exactly Na for A, just Nt for T, just Ng for G, and just Nc for C, divided by 1,000,000,007.

Input

> Na Nt Ng Nc
> m
> Nonterminal 1: Symbol 11 Symbol 12 ... Symbol 1n1
> Non-terminal symbol 2: Symbol 21 Symbol 22 ... Symbol 2n2
> ...
> Non-terminal symbol m: symbol m1 symbol m2 ... symbol mnm
>

0 ≤ Na, Nt, Ng, Nc ≤ 50

1 ≤ m ≤ 50

1 ≤ ni ≤ 10

1 ≤ Length of the character string representing the symbol ≤ 20 (* Note that it is not the length of the character string that matches the symbol)

Output

The remainder of the total number divided by 1,000,000,007

Examples

Input

1 0 1 0
3
dna: a b
a: [AT]
b: [GC]

Output

1

Input

1 1 1 2
1
k: [ATG] [ATG] [ATG] [C] [C]

Output

6

Input

3 1 1 1
3
inv: at b b b
at: [ATG] b
b: [C]

Output

0

```python
from collections import defaultdict
import sys
def solve():
    readline = sys.stdin.readline
    write = sys.stdout.write
    MOD = 10**9 + 7
    Na, Nt, Ng, Nc = map(int, readline().split())
    L = Na + Nt + Ng + Nc
    M = int(readline())
    MP = {}
    S = []
    for i in range(M):
        s = readline().strip()
        s1, s2 = s.split(": ")
        MP[s1] = s2.split(" ")
        S.append(s1)
    R = []
    memo = {}
    def dfs(s):
        if s in memo:
            return memo[s]
        r = []
        for e in MP[s]:
            if e[0] == "[":
                w = 0
                for v in map("ATGC".index, e[1:-1]):
                    w |= 1 << v
                r.append(w)
            else:
                r0 = dfs(e)
                if r0 is None:
                    return None
                r.extend(r0)
        if len(r) > L:
            return None
        memo[s] = r
        return r
    res = dfs(S[0])
    if res is None or len(res) < L:
        write("0\n")
        return
    L = len(res)

    T = [defaultdict(int) for i in range(L+1)]
    T[0][Na, Nt, Ng, Nc] = 1
    for k in range(L):
        s = res[k]
        p0 = s & 1; p1 = s & 2; p2 = s & 4; p3 = s & 8
        T1 = T[k+1]
        for (a, b, c, d), v in T[k].items():
            v %= MOD
            if p0 and a:
                T1[a-1, b, c, d] += v
            if p1 and b:
                T1[a, b-1, c, d] += v
            if p2 and c:
                T1[a, b, c-1, d] += v
            if p3 and d:
                T1[a, b, c, d-1] += v
    write("%d\n" % (T[L][0, 0, 0, 0] % MOD))
solve()

```


p01852 Finger Counting

Problem statement

Meatishi can increase or decrease the number of fingers.
There are n buns in front of Nikunishi-kun.
Meatishi is trying to count the number of steamed buns by breaking his finger.
There are only two shapes that Nishikun's fingers can take, whether they are broken or not.
Nikunishi understands binary numbers.
Nikunishi-kun can count numbers by associating each finger with a binary digit.
Nikunishi doesn't understand the logarithm.
Find the minimum number of fingers needed to count the buns instead of Nishikun.

input

n

Constraint

* An integer
* 0 ≤ n ≤ 1018

output

Print the answer on one line, and print a newline at the end.

sample

Sample input 1

0

Sample output 1

0

Sample input 2

Four

Sample output 2

3

Sample input 3

31

Sample output 3

Five

Sample input 4

36028797018963968

Sample output 4

56

Example

Input

0

Output

0


p02274 The Number of Inversions

For a given sequence $A = \\{a_0, a_1, ... a_{n-1}\\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
cnt = 0 // the number of inversions
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
	swap(A[j], A[j-1])
	cnt++

return cnt

For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded.

Constraints

* $ 1 \leq n \leq 200,000$
* $ 0 \leq a_i \leq 10^9$
* $a_i$ are all different

Input

In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters.

Examples

Input

5
3 5 2 1 4

Output

6

Input

3
3 1 2

Output

2

```python
import bisect
#int bit[n+1],n

def sum(i):#[1,i]のsumを求める
    s = 0
    while(i > 0):
        s += bit[i]
        i = i&(i-1)
    return s

def add(i,x):#i番目にxを加算 i & (-i):iの最後の1のbit
    while(i <= n):
        bit[i] += x
        i += i & (-i)

n = int(input())
a = list(map(int,input().split()))
aa = sorted(a)

bit = [0]

for i in range(n):
    a[i] = bisect.bisect_left(aa,a[i])+1
    bit.append(0)

ans = 0

for i in range(n):
    ans += (i - sum(a[i]))
    add(a[i],1)

print(ans)

```


p02421 Card Game

Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card. The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.

Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.

Constraints

* n ≤ 1000
* The length of the string ≤ 100

Input

In the first line, the number of cards n is given. In the following n lines, the cards for n turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.

Output

Print the final scores of Taro and Hanako respectively. Put a single space character between them.

Example

Input

3
cat dog
fish fish
lion tiger

Output

1 7

```python
n = int(input())
t = 0
h = 0

for _ in range(n):
    tc, hc = input().split()

    if tc > hc:
        t += 3
    elif tc < hc:
        h += 3
    else:
        t += 1
        h += 1

print(t, h)
```


1003_A. Polycarp's Pockets

Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.

For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two pockets as follows: [1, 2, 3], [2, 3, 4].

Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.

Input

The first line of the input contains one integer n (1 ≤ n ≤ 100) — the number of coins.

The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100) — values of coins.

Output

Print only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket.

Examples

Input

6
1 2 4 3 3 2

Output

2

Input

1
100

Output

1

```python
n = int(input())
mn = list(map(int, input().split()))
k = 1
for i in range(1, 101):
    s = mn.count(i)
    if s > k:
        k = s
print(k)
```


1027_B. Numbers on the Chessboard

You are given a chessboard of size n × n. It is filled with numbers from 1 to n^2 in the following way: the first ⌈ (n^2)/(2) ⌉ numbers from 1 to ⌈ (n^2)/(2) ⌉ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest n^2 - ⌈ (n^2)/(2) ⌉ numbers from ⌈ (n^2)/(2) ⌉ + 1 to n^2 are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation ⌈x/y⌉ means division x by y rounded up.

For example, the left board on the following picture is the chessboard which is given for n=4 and the right board is the chessboard which is given for n=5.

<image>

You are given q queries. The i-th query is described as a pair x_i, y_i. The answer to the i-th query is the number written in the cell x_i, y_i (x_i is the row, y_i is the column). Rows and columns are numbered from 1 to n.

Input

The first line contains two integers n and q (1 ≤ n ≤ 10^9, 1 ≤ q ≤ 10^5) — the size of the board and the number of queries.

The next q lines contain two integers each. The i-th line contains two integers x_i, y_i (1 ≤ x_i, y_i ≤ n) — description of the i-th query.

Output

For each query from 1 to q print the answer to this query. The answer to the i-th query is the number written in the cell x_i, y_i (x_i is the row, y_i is the column). Rows and columns are numbered from 1 to n. Queries are numbered from 1 to q in order of the input.

Examples

Input

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

Output

1
8
16
13
4

Input

5 4
2 1
4 2
3 3
3 4

Output

16
9
7
20

Note

Answers to the queries from examples are on the board in the picture from the problem statement.

```python
import sys

n,q=map(int,sys.stdin.readline().strip().split())
nc=n
# print(n,q)

if(n%2==0):
    n2=int((n*n)/2)
else:
    n2=int((n*n)/2)+1
n1=int(n/2)
if(1==1):
    for i in range(q):
        x,y=map(int,sys.stdin.readline().strip().split())
        # print(n,q,x,y)
        x1=int(x/2)
        y1=int(y/2)
        op=0
        if(x%2!=0):

            if(y%2!=0):
                if(x>1):
                    op=n*(x1)
                op=op+1+(y1)
            else:
                op=n2+(n*x1)+y1

        else:
            if(y%2==0):
                if(n%2==0):
                    op=n1
                else:
                    op=n1+1
                op=op+(n*(x1-1))
                op=op+y1

            else:

                op=n2+n1+(n*(x1-1))+(y1)+1
        print(op)
```


1091_D. New Year and the Permutation Concatenation

Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence p. For example, if n = 3, then p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence will be n ⋅ n!.

Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We call the sequence (p_i, p_{i+1}, ..., p_{j-1}, p_j) a subarray of p. Its length is defined as the number of its elements, i.e., j - i + 1. Its sum is the sum of all its elements, i.e., ∑_{k=i}^j p_k.

You are given n. Find the number of subarrays of p of length n having sum (n(n+1))/(2). Since this number may be large, output it modulo 998244353 (a prime number).

Input

The only line contains one integer n (1 ≤ n ≤ 10^6), as described in the problem statement.

Output

Output a single integer — the number of subarrays of length n having sum (n(n+1))/(2), modulo 998244353.

Examples

Input

3

Output

9

Input

4

Output

56

Input

10

Output

30052700

Note

In the first sample, there are 16 subarrays of length 3. In order of appearance, they are:

[1, 2, 3], [2, 3, 1], [3, 1, 3], [1, 3, 2], [3, 2, 2], [2, 2, 1], [2, 1, 3], [1, 3, 2], [3, 2, 3], [2, 3, 1], [3, 1, 3], [1, 3, 1], [3, 1, 2], [1, 2, 3], [2, 3, 2], [3, 2, 1].

Their sums are 6, 6, 7, 6, 7, 5, 6, 6, 8, 6, 7, 5, 6, 6, 7, 6. As (n(n+1))/(2) = 6, the answer is 9.


1110_B. Tape

You have a long stick, consisting of m segments enumerated from 1 to m. Each segment is 1 centimeter long. Sadly, some segments are broken and need to be repaired.

You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece of tape of integer length t placed at some position s will cover segments s, s+1, …, s+t-1.

You are allowed to cover non-broken segments; it is also possible that some pieces of tape will overlap.

Time is money, so you want to cut at most k continuous pieces of tape to cover all the broken segments. What is the minimum total length of these pieces?

Input

The first line contains three integers n, m and k (1 ≤ n ≤ 10^5, n ≤ m ≤ 10^9, 1 ≤ k ≤ n) — the number of broken segments, the length of the stick and the maximum number of pieces you can use.

The second line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ m) — the positions of the broken segments. These integers are given in increasing order, that is, b_1 < b_2 < … < b_n.

Output

Print the minimum total length of the pieces.

Examples

Input

4 100 2
20 30 75 80

Output

17

Input

5 100 3
1 2 4 60 87

Output

6

Note

In the first example, you can use a piece of length 11 to cover the broken segments 20 and 30, and another piece of length 6 to cover 75 and 80, for a total length of 17.

In the second example, you can use a piece of length 4 to cover broken segments 1, 2 and 4, and two pieces of length 1 to cover broken segments 60 and 87.

```python
n, m, k = (int(x) for x in input().split())
b = [int(x) for x in input().split()]

deltaB = sorted([b[i + 1] - b[i] for i in range(n - 1)])

print(sum(deltaB[:n - k]) + k)

```


1158_C. Permutation recovery

Vasya has written some permutation p_1, p_2, …, p_n of integers from 1 to n, so for all 1 ≤ i ≤ n it is true that 1 ≤ p_i ≤ n and all p_1, p_2, …, p_n are different. After that he wrote n numbers next_1, next_2, …, next_n. The number next_i is equal to the minimal index i < j ≤ n, such that p_j > p_i. If there is no such j let's let's define as next_i = n + 1.

In the evening Vasya went home from school and due to rain, his notebook got wet. Now it is impossible to read some written numbers. Permutation and some values next_i are completely lost! If for some i the value next_i is lost, let's say that next_i = -1.

You are given numbers next_1, next_2, …, next_n (maybe some of them are equal to -1). Help Vasya to find such permutation p_1, p_2, …, p_n of integers from 1 to n, that he can write it to the notebook and all numbers next_i, which are not equal to -1, will be correct.

Input

The first line contains one integer t — the number of test cases (1 ≤ t ≤ 100 000).

Next 2 ⋅ t lines contains the description of test cases,two lines for each. The first line contains one integer n — the length of the permutation, written by Vasya (1 ≤ n ≤ 500 000). The second line contains n integers next_1, next_2, …, next_n, separated by spaces (next_i = -1 or i < next_i ≤ n + 1).

It is guaranteed, that the sum of n in all test cases doesn't exceed 500 000.

In hacks you can only use one test case, so T = 1.

Output

Print T lines, in i-th of them answer to the i-th test case.

If there is no such permutations p_1, p_2, …, p_n of integers from 1 to n, that Vasya could write, print the only number -1.

In the other case print n different integers p_1, p_2, …, p_n, separated by spaces (1 ≤ p_i ≤ n). All defined values of next_i which are not equal to -1 should be computed correctly p_1, p_2, …, p_n using defenition given in the statement of the problem. If there exists more than one solution you can find any of them.

Example

Input

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

Output

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

Note

In the first test case for permutation p = [1, 2, 3] Vasya should write next = [2, 3, 4], because each number in permutation is less than next. It's easy to see, that it is the only satisfying permutation.

In the third test case, any permutation can be the answer because all numbers next_i are lost.

In the fourth test case, there is no satisfying permutation, so the answer is -1.

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

T = int(input())
for _ in range(T):
    n = int(input())
    l = list(map(int, input().split()))

    stack = []
    out = [-1] * n
    curr = 0
    works = True
    for i in range(n):
        while stack and stack[-1][0] == i:
            _, j = stack.pop()
            curr += 1
            out[j] = curr

        nex = l[i] - 1
        if nex == -2:
            curr += 1
            out[i] = curr
        else:
            if stack and nex > stack[-1][0]:
                works = False
            else:
                stack.append((nex, i))

    while stack:
        _, j = stack.pop()
        curr += 1
        out[j] = curr

    if works:
        print(*out)
    else:
        print(-1)
```


1180_B. Nick and Array

Nick had received an awesome array of integers a=[a_1, a_2, ..., a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 ⋅ a_2 ⋅ ... a_n of its elements seemed to him not large enough.

He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index i (1 ≤ i ≤ n) and do a_i := -a_i - 1.

For example, he can change array [3, -1, -4, 1] to an array [-4, -1, 3, 1] after applying this operation to elements with indices i=1 and i=3.

Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index.

Help Kolya and print the array with the maximal possible product of elements a_1 ⋅ a_2 ⋅ ... a_n which can be received using only this operation in some order.

If there are multiple answers, print any of them.

Input

The first line contains integer n (1 ≤ n ≤ 10^{5}) — number of integers in the array.

The second line contains n integers a_1, a_2, …, a_n (-10^{6} ≤ a_i ≤ 10^{6}) — elements of the array

Output

Print n numbers — elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array.

If there are multiple answers, print any of them.

Examples

Input

4
2 2 2 2

Output

-3 -3 -3 -3

Input

1
0

Output

0

Input

3
-3 -3 2

Output

-3 -3 2

```python
n=int(input())
list1=[*map(int,input().split())]
list2=[]
if n%2==0:
    for element in list1:
        if element>=0:
            print(-element-1)
        else:
            print(element)
else:
    for element in list1:
        if element>=0:
            list2.append(-element-1)
        else:
            list2.append(element)
    index1=list2.index(min(list2))
    for i in range(n):
        if i!=index1:
            print(list2[i],end=" ")
        else :
            print((-list2[i]-1),end=" ")

```


1199_B. Water Lily

While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surface.

<image>

Suppose that the lily grows at some point A on the lake bottom, and its stem is always a straight segment with one endpoint at point A. Also suppose that initially the flower was exactly above the point A, i.e. its stem was vertical. Can you determine the depth of the lake at point A?

Input

The only line contains two integers H and L (1 ≤ H < L ≤ 10^{6}).

Output

Print a single number — the depth of the lake at point A. The absolute or relative error should not exceed 10^{-6}.

Formally, let your answer be A, and the jury's answer be B. Your answer is accepted if and only if \frac{|A - B|}{max{(1, |B|)}} ≤ 10^{-6}.

Examples

Input

1 2

Output

1.5000000000000

Input

3 5

Output

2.6666666666667

```python
import math

h, l = input().split()
h = int(h)
l = int(l)
a = float((pow(l,2)-pow(h,2))/(2*h))
print(a)
```


1216_A. Prefixes

Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n.

He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arbitrary number of times (possibly, zero): choose some position in his string and replace the letter on this position with the other letter (i.e. replace 'a' with 'b' or replace 'b' with 'a'). Nikolay can use no letters except 'a' and 'b'.

The prefix of string s of length l (1 ≤ l ≤ n) is a string s[1..l].

For example, for the string s="abba" there are two prefixes of the even length. The first is s[1...2]="ab" and the second s[1...4]="abba". Both of them have the same number of 'a' and 'b'.

Your task is to calculate the minimum number of operations Nikolay has to perform with the string s to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.

Input

The first line of the input contains one even integer n (2 ≤ n ≤ 2⋅10^{5}) — the length of string s.

The second line of the input contains the string s of length n, which consists only of lowercase Latin letters 'a' and 'b'.

Output

In the first line print the minimum number of operations Nikolay has to perform with the string s to modify it so that every its prefix of even length has an equal amount of letters 'a' and 'b'.

In the second line print the string Nikolay obtains after applying all the operations. If there are multiple answers, you can print any of them.

Examples

Input

4
bbbb

Output

2
abba

Input

6
ababab

Output

0
ababab

Input

2
aa

Output

1
ba

Note

In the first example Nikolay has to perform two operations. For example, he can replace the first 'b' with 'a' and the last 'b' with 'a'.

In the second example Nikolay doesn't need to do anything because each prefix of an even length of the initial string already contains an equal amount of letters 'a' and 'b'.

```python
l = int(input())
s = list(input().strip())

ct = 0
for i in range(0,l-1,2):
    if s[i] == s[i+1]:
        ct += 1
        if s[i] == 'a':
            s[i] = 'b'
        else:
            s[i] = 'a'
print(ct)
print(''.join(s))
```


1239_B. The World Is Just a Programming Task (Hard Version)

This is a harder version of the problem. In this version, n ≤ 300 000.

Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.

To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.

We remind that bracket sequence s is called correct if:

  * s is empty;
  * s is equal to "(t)", where t is correct bracket sequence;
  * s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.

For example, "(()())", "()" are correct, while ")(" and "())" are not.

The cyclical shift of the string s of length n by k (0 ≤ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".

Cyclical shifts i and j are considered different, if i ≠ j.

Input

The first line contains an integer n (1 ≤ n ≤ 300 000), the length of the string.

The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".

Output

The first line should contain a single integer — the largest beauty of the string, which can be achieved by swapping some two characters.

The second line should contain integers l and r (1 ≤ l, r ≤ n) — the indices of two characters, which should be swapped in order to maximize the string's beauty.

In case there are several possible swaps, print any of them.

Examples

Input

10
()()())(()

Output

5
8 7

Input

12
)(()(()())()

Output

4
5 10

Input

6
)))(()

Output

0
1 1

Note

In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.

In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.

In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.

```python
def get_bal():
    bal = [0] * n
    bal[0] = u[0]
    for i in range(1, n):
        bal[i] = bal[i - 1] + u[i]
    min_b = min(bal)
    ans = 0
    for i in range(n):
        if bal[i] == min_b:
            ans += 1
    return ans

n = int(input())
u = list(input())
for i in range(n):
    if u[i] == '(':
        u[i] = 1
    else:
        u[i] = -1
if sum(u) != 0:
    print(0)
    print(1, 1)
    exit()
ind = (-1, -1)
ans = -1
for i in range(n):
    for j in range(i, n):
        u[i], u[j] = u[j], u[i]
        ans_i = get_bal()
        u[i], u[j] = u[j], u[i]
        if ans_i > ans:
            ans = ans_i
            ind = (i + 1, j + 1)
print(ans)
print(ind[0], ind[1])

```