p01322 Lottery Checker

You have successfully completed your studies and are preparing to move from near Komaba to near Hongo. As I was organizing my house, I found a lot of lottery tickets I bought last year. After confirming the exchange deadline, I have to cash in by tomorrow, but it is troublesome to go to the lottery counter for a small amount of money because I am not ready to move at all. So you decide to find out how much you can win.

The lottery consists of eight digits. The winning number is also composed of 8 digits and a number and'*', and if the lottery you have and the number part match, the winning money will be paid according to the winning number.

For example, if the lottery number you have is "12345678", you will win if the winning number is "******* 8" or "**** 5678", but the winning number is "**". If it is ** 4678 ", you will not win. There can be multiple winning numbers, and the winnings will be paid independently for each. However, the winning numbers are chosen so that one lottery does not win more than one winning number. For example, if there are two winning numbers, "******* 8" and "**** 5678", "12345678" will win both, so such a winning number will be selected. There is no one to be done.

Your job is to write a program that outputs how much winning money you will get for the lottery number you have and the lottery winning number given as input.

Notes on Test Cases

Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.

When n is 0, it indicates the end of input.

<!-

Input

The input is given in the following format.

n m
N1 M1
...
Nn Mn
B1
...
Bm

In the first line, the number of winning numbers n (1 ≤ n ≤ 100) and the number of lottery tickets in possession m (1 ≤ m ≤ 1000) are given as integers.

In the next n lines, each line is given a winning number Ni and a winnings Mi (1 ≤ Mi ≤ 1000000). Winnings are integers. The format of the winning number is as described in the question text.

The next m lines will give you the number of the lottery you have.

Output

Output the total amount of winnings.

Examples

Input

3 3
*******1 100
******22 1000
11111112 1000000
01203291
02382022
11111111
10 10
****3228 149416
****3992 198635
****4286 77783
****4843 225244
***49835 231046
***59393 379996
*5763748 437345
*6726222 58054
*8117882 16375
*9244339 537727
77885716
96726222
26971031
66652868
89599648
37772338
64679621
65479161
92959393
57855682
0 0

Output

1200
438050

Input

3 3
*******1 100
******22 1000
11111112 1000000
01203291
02382022
11111111

Output

1200

Input

10 10
****3228 149416
****3992 198635
****4286 77783
****4843 225244
***49835 231046
***59393 379996
*5763748 437345
*6726222 58054
*8117882 16375
*9244339 537727
77885716
96726222
26971031
66652868
89599648
37772338
64679621
65479161
92959393
57855682

Output

438050

```python
import re
while 1:
    n,m=map(int,input().split())
    if n==0:break
    p=[];s=0
    for _ in [0]*n:
        n,M=input().replace('*','[0-9]').split()
        p.append([re.compile(n),int(M)])
    for _ in [0]*m:
        l=input()
        for n,M in p:
            if n.search(l):
                s+=M;break
    print(s)
```


p01490 HullMarathon

Example

Input

4
5
8
58
85

Output

2970.000000000

```python
from itertools import permutations
from math import acos, sin, cos, pi
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
    N = int(readline())
    R = [int(readline()) for i in range(N)]
    R.sort(reverse=1)

    ans = 0
    for l in range(3, N+1):
        for rs in permutations(R[:l]):
            C = [rs[i]*rs[i-l+1] for i in range(l)]
            if C.index(min(C)) != 0:
                continue

            left = 0; right = pi+1e-9
            while right - left > 1e-9:
                mid = (left + right) / 2
                s = mid
                cv = cos(mid)
                for i in range(1, l):
                    s += acos(C[0]*cv/C[i])
                if s > 2*pi:
                    right = mid
                else:
                    left = mid
            if left < 1e-9:
                continue
            res = C[0]*sin(left)
            cv = cos(left)
            v2 = (C[0]*cos(left))**2
            for i in range(1, l):
                res += (C[i]**2 - v2)**.5
            ans = max(ans, res)
    ans /= 2
    write("%.16f\n" % ans)
solve()

```


p01803 Airport Codes

Airport Codes

Airport code

In the Kingdom of JAG, airport codes are assigned to each domestic airport for identification.

Airport codes are assigned according to the following rules based on the name of the airport in lowercase English alphabet:

1. Extract the first letter of the name and the letter immediately after the vowel (a, i, u, e, o) in order.
2. If the extracted character string is less than k characters, use it as the airport code, and if it is k characters or more, use the first k characters of the extracted character string as the airport code.

For example, when k = 3, haneda is assigned the code hnd, oookayama is assigned the code ooo, and tsu is assigned the code t.

However, with this code assignment method, the same code may be assigned even at airports with different names, which causes confusion. Given a list of airport names, determine if all airport codes can be different, find the minimum k that can make all airport codes different if possible, and if not possible. Create a program to convey this.

Input

The input consists of 100 or less datasets. Each dataset is given in the following format.

> n
> s1
> ...
> sn

The number of airports n (2 ≤ n ≤ 50) is given as an integer on the first line, and the name si of the airport is given as a string on each of the following n lines. Airport names consist only of lowercase English alphabets from'a'to'z', all with 1 to 50 characters. Also, the names of the airports given are all different. That is, when 1 ≤ i <j ≤ n, si ≠ sj is satisfied.

The end of the input is indicated by a line consisting of only one zero.

Output

For each dataset, if all airports can be assigned different airport codes, output such a minimum k on one line. If not possible, output -1 on one line.

Sample Input

3
haneda
oookayama
tsu
2
azusa
azishirabe
2
snuke
snake
Four
haneda
honda
hanamaki
hawaii
0

Output for Sample Input

1
Four
-1
3

Example

Input

3
haneda
oookayama
tsu
2
azusa
azishirabe
2
snuke
snake
4
haneda
honda
hanamaki
hawaii
0

Output

1
4
-1
3

```python
while 1:
    n=int(input())
    if not n:break
    l=[]
    m=0
    for _ in range(n):
        s=input()
        a=s[0]
        for i,t in enumerate(s[:-1]):
            if any(t==c for c in'aiueo'):
                a+=s[i+1]
        m=max(m,len(a))
        l.append(a)
    for k in range(m+1):
        if len(set(t[:k]for t in l))==n:
            print(k)
            break
    else:
        print(-1)

```


p01938 A-Z-

A: A-Z-

problem

There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.

<image>

Also, the board has one piece in the'A'square.

You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.

* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.

As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.

Input format

Input is given on one line.

S

S represents the string you receive.

Constraint

* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.

Output format

Output in one line how many times you stepped on the'A'square.

Input example 1

AIZU

Output example 1

2

* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)

Input example 2

HOKKAIDO

Output example 2

Four

Example

Input

AIZU

Output

2

```python
S = input()
cur = 'A'
ans = 0
for i in range(len(S)):
    if(S[i] == cur):
        ans += 1
    else:
        if(cur > S[i]):
            ans += 1
        cur = S[i]
print(ans)

```


p02371 Diameter of a Tree

Diameter of a Tree

Given a tree T with non-negative weight, find the diameter of the tree.

The diameter of a tree is the maximum distance between two nodes in a tree.

Constraints

* 1 ≤ n ≤ 100,000
* 0 ≤ wi ≤ 1,000

Input

n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output

Print the diameter of the tree in a line.

Examples

Input

4
0 1 2
1 2 1
1 3 3

Output

5

Input

4
0 1 1
1 2 2
2 3 4

Output

7

```python
import sys
readline = sys.stdin.readline
from collections import deque
from math import isinf
INF = float("inf")
sys.setrecursionlimit(200000)
n = int(readline())
G = [[] for _ in range(n)]
D = [INF] * n
for _ in [0] * (n - 1):
    s, t, w = map(int, readline().split())
    G[s].append([t, w])
    G[t].append([s, w])
def bfs(s, D):
    dq = deque([s])
    D = [INF] * n
    D[s] = 0
    while dq:
        u = dq.popleft()
        for i in range(len(G[u])):
            e = G[u][i]
            if isinf(D[e[0]]):
                D[e[0]] = D[u] + e[1]
                dq.append(e[0])
    return D
D = bfs(0, D)
maxv = 0
tgt = 0
for i in range(n):
    if isinf(D[i]): continue
    if maxv < D[i]:
        maxv = D[i]
        tgt = i
D = bfs(tgt, D)
print(max(D[i] for i in range(n) if not isinf(D[i])))
```


1011_E. Border

Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.

There are n banknote denominations on Mars: the value of i-th banknote is a_i. Natasha has an infinite number of banknotes of each denomination.

Martians have k fingers on their hands, so they use a number system with base k. In addition, the Martians consider the digit d (in the number system with base k) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base k is d, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.

Determine for which values d Natasha can make the Martians happy.

Natasha can use only her banknotes. Martians don't give her change.

Input

The first line contains two integers n and k (1 ≤ n ≤ 100 000, 2 ≤ k ≤ 100 000) — the number of denominations of banknotes and the base of the number system on Mars.

The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — denominations of banknotes on Mars.

All numbers are given in decimal notation.

Output

On the first line output the number of values d for which Natasha can make the Martians happy.

In the second line, output all these values in increasing order.

Print all numbers in decimal notation.

Examples

Input

2 8
12 20

Output

2
0 4

Input

3 10
10 20 30

Output

1
0

Note

Consider the first test case. It uses the octal number system.

If you take one banknote with the value of 12, you will get 14_8 in octal system. The last digit is 4_8.

If you take one banknote with the value of 12 and one banknote with the value of 20, the total value will be 32. In the octal system, it is 40_8. The last digit is 0_8.

If you take two banknotes with the value of 20, the total value will be 40, this is 50_8 in the octal system. The last digit is 0_8.

No other digits other than 0_8 and 4_8 can be obtained. Digits 0_8 and 4_8 could also be obtained in other ways.

The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.

```python
from functools import reduce
from math import gcd
n, k = map(int, input().split())
A = list(map(int, input().split()))
G = gcd(k, reduce(lambda x,y:gcd(x,y),A))
print(k // G)
print(*list(range(0, k, G)))
```


1036_F. Relatively Prime Powers

Consider some positive integer x. Its prime factorization will be of form x = 2^{k_1} ⋅ 3^{k_2} ⋅ 5^{k_3} ⋅ ...

Let's call x elegant if the greatest common divisor of the sequence k_1, k_2, ... is equal to 1. For example, numbers 5 = 5^1, 12 = 2^2 ⋅ 3, 72 = 2^3 ⋅ 3^2 are elegant and numbers 8 = 2^3 (GCD = 3), 2500 = 2^2 ⋅ 5^4 (GCD = 2) are not.

Count the number of elegant integers from 2 to n.

Each testcase contains several values of n, for each of them you are required to solve the problem separately.

Input

The first line contains a single integer T (1 ≤ T ≤ 10^5) — the number of values of n in the testcase.

Each of the next T lines contains a single integer n_i (2 ≤ n_i ≤ 10^{18}).

Output

Print T lines — the i-th line should contain the number of elegant numbers from 2 to n_i.

Example

Input

4
4
2
72
10

Output

2
1
61
6

Note

Here is the list of non-elegant numbers up to 10:

  * 4 = 2^2, GCD = 2;
  * 8 = 2^3, GCD = 3;
  * 9 = 3^2, GCD = 2.

The rest have GCD = 1.

```python
from math import sqrt, log2
from sys import stdin
from bisect import bisect
import time

def all_primes(n):
    res = []
    for i in range(1, n+1):
        prime = True
        for j in range(2, min(int(sqrt(i))+2, i)):
            if i % j == 0:
                prime = False
                break
        if prime: res.append(i)
    return res

def count_pow_nums(n, p):  #don't count 1
    top = int(pow(n, 1.0/p))
    if pow(top+2, p) <= n:
        return top+1
    elif pow(top+1, p) <= n:
        return top
    elif pow(top, p) <= n:
        return top-1
    else:
        return top-2
primes = all_primes(64)
num_set=set()
max_n = 1000000000000000000
for pi in range(3, len(primes)):
    p = primes[pi]
    cnt = count_pow_nums(max_n, p)
    for n in range(2, cnt+5):
        sq2 = round(sqrt(n))
        sq3 = round(pow(n, 1/3))
        if sq2**2 != n and sq3**3 != n:
            num = pow(n, p)
            if num <= max_n:
                num_set.add(num)
nums = sorted(num_set)
t = int(stdin.readline())
for i in range(t):
    n = int(stdin.readline())
    ans = n-1-count_pow_nums(n, 2)-count_pow_nums(n, 3)+count_pow_nums(n, 6)
    ans -= bisect(nums, n)
    print(ans)

```


1059_E. Split the Tree

You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path.

A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}.

Input

The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path.

The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree.

The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree.

Output

Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1.

Examples

Input

3 1 3
1 2 3
1 1

Output

3

Input

3 3 6
1 2 3
1 1

Output

2

Input

1 1 10000
10001

Output

-1

Note

In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}.

In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}.

In the third sample it is impossible to split the tree.

```python
from collections import defaultdict
import sys

def rec(n, l, s):
    # dp[i] is a doctionary, where key is the chain length
    # and value is the weight at node i
    dp = [{} for _ in range(n)]
    ans = 0
    for cur in range(n - 1, -1, -1):
        child_of_cur = children.get(cur, None)
        if not child_of_cur:
            dp[cur][1] = weight[cur]
            continue
        ans += len(child_of_cur) - 1
        cur_weight = weight[cur]
        for ch in child_of_cur:
            for ln, child_weight in dp[ch].items():
                if ln == l:
                    continue
                agg_weight = cur_weight + child_weight
                if agg_weight > s:
                    continue
                if ln + 1 not in dp[cur]:
                    dp[cur][ln + 1] = agg_weight
                dp[cur][ln + 1] = min(dp[cur][ln + 1], agg_weight)

        if not dp[cur]:
            ans += 1
            dp[cur][1] = weight[cur]

    return ans + 1

weight = []
children = defaultdict(set)
n, l, s = map(int, sys.stdin.readline().split())
for w in map(int, sys.stdin.readline().split()):
    if w > s:
        print(-1)
        exit()
    weight.append(w)
if n == 1:
    print(-1 if weight[0] > s else 1)
    exit()
for i, v in enumerate(map(int, sys.stdin.readline().split())):
    children[v -1].add(i + 1)
print(rec(n,l,s))
```


1081_A. Definite Game

Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games.

He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer x that x<n and x is not a divisor of n, then subtract x from n. The goal of the player is to minimize the value of n in the end.

Soon, Chouti found the game trivial. Can you also beat the game?

Input

The input contains only one integer in the first line: v (1 ≤ v ≤ 10^9), the initial value of n.

Output

Output a single integer, the minimum value of n the player can get.

Examples

Input

8

Output

1

Input

1

Output

1

Note

In the first example, the player can choose x=3 in the first turn, then n becomes 5. He can then choose x=4 in the second turn to get n=1 as the result. There are other ways to get this minimum. However, for example, he cannot choose x=2 in the first turn because 2 is a divisor of 8.

In the second example, since n=1 initially, the player can do nothing.

```python
v = int(input())
print(2 if v == 2 else 1)

```


1100_A. Roman and Browser

This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.

He decided to accomplish this by closing every k-th (2 ≤ k ≤ n - 1) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be b) and then close all tabs with numbers c = b + i ⋅ k that satisfy the following condition: 1 ≤ c ≤ n and i is an integer (it may be positive, negative or zero).

For example, if k = 3, n = 14 and Roman chooses b = 8, then he will close tabs with numbers 2, 5, 8, 11 and 14.

After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it e) and the amount of remaining social network tabs (s). Help Roman to calculate the maximal absolute value of the difference of those values |e - s| so that it would be easy to decide what to do next.

Input

The first line contains two integers n and k (2 ≤ k < n ≤ 100) — the amount of tabs opened currently and the distance between the tabs closed.

The second line consists of n integers, each of them equal either to 1 or to -1. The i-th integer denotes the type of the i-th tab: if it is equal to 1, this tab contains information for the test, and if it is equal to -1, it's a social network tab.

Output

Output a single integer — the maximum absolute difference between the amounts of remaining tabs of different types |e - s|.

Examples

Input

4 2
1 1 -1 1

Output

2

Input

14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1

Output

9

Note

In the first example we can choose b = 1 or b = 3. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, e = 2 and s = 0 and |e - s| = 2.

In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.

```python
from collections import Counter
import math
n,m=map(int,input().split())
l=list(map(int,input().split()))
c=Counter(l)
a1=c[1]
a2=c[-1]
i=0
s=[]
a=0
b=0

while(i<m):
	for j in range(i,n,m):
		if l[j]>0:
			a+=1
		else:
			b+=1
	s+=[abs(a1-a2+b-a)]
	a=0
	b=0
	i+=1

print(max(s))
```


1121_E. Once in a casino

One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.

A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.

Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.

Input

The first line contains a single integer n (2 ≤ n ≤ 10^5) standing for the length of numbers a and b.

The next two lines contain numbers a and b, each one on a separate line (10^{n-1} ≤ a, b < 10^n).

Output

If it is impossible to win the jackpot, print a single integer -1.

Otherwise, the first line must contain the minimal possible number c of coins the player has to spend.

min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1≤ d_i≤ n - 1, s_i = ± 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change).

Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.

Examples

Input

3
223
322

Output

2
1 1
2 -1

Input

2
20
42

Output

2
1 1
1 1

Input

2
35
44

Output

-1

Note

In the first example, we can make a +1 operation on the two first digits, transforming number 223 into 333, and then make a -1 operation on the last two digits, transforming 333 into 322.

It's also possible to do these operations in reverse order, which makes another correct answer.

In the last example, one can show that it's impossible to transform 35 into 44.

```python
def main():
    n = int(input())
    a = list(map(int, (x for x in input())))
    b = list(map(int, (x for x in input())))
    x = [0] * (n - 1)
    x[0] = b[0] - a[0]
    for i in range(1, n - 1):
        x[i] = b[i] - a[i] - x[i - 1]
    if a[n - 1] + x[n - 2] != b[n - 1]:
        print(-1)
        return
    cnt = sum(map(abs, x))  # prevbug: ftl
    print(cnt)
    cnt = min(cnt, 10 ** 5)
    index = 0

    def handle_zero_nine(cur_zero):
        nonlocal cnt
        nxt = index + 1
        # cur_zero = True prevbug: preserved this line
        while True:
            if cur_zero and a[nxt + 1] != 9:
                break
            if not cur_zero and a[nxt + 1] != 0:
                break
            nxt += 1
            cur_zero = not cur_zero
        while nxt > index:
            if cnt == 0:
                break
            if cur_zero:
                print(nxt + 1, 1)
                a[nxt] += 1
                a[nxt + 1] += 1
            else:
                print(nxt + 1, -1)
                a[nxt] -= 1
                a[nxt + 1] -= 1
            nxt -= 1
            cnt -= 1
            # print(a)
            cur_zero = not cur_zero

    while cnt > 0:
        if a[index] == b[index]:
            index += 1
            continue
        elif a[index] > b[index] and a[index + 1] == 0:
            handle_zero_nine(True)
        elif a[index] < b[index] and a[index + 1] == 9:
            handle_zero_nine(False)
        elif a[index] > b[index]:
            print(index + 1, -1)
            a[index] -= 1
            a[index + 1] -= 1
            cnt -= 1
            # print(a)
        elif a[index] < b[index]:
            print(index + 1, 1)
            a[index] += 1
            a[index + 1] += 1
            cnt -= 1
            # print(a)

if __name__ == '__main__':
    main()

```


116_D. Lawnmower

You have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either grass or weeds. For example, a 4 × 5 garden may look as follows (empty cells denote grass):

<image>

You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell (1, 1). At any moment of time you are facing a certain direction — either left or right. And initially, you face right.

In one move you can do either one of these:

1) Move one cell in the direction that you are facing.

  * if you are facing right: move from cell (r, c) to cell (r, c + 1)

<image>

  * if you are facing left: move from cell (r, c) to cell (r, c - 1)

<image>

2) Move one cell down (that is, from cell (r, c) to cell (r + 1, c)), and change your direction to the opposite one.

  * if you were facing right previously, you will face left

<image>

  * if you were facing left previously, you will face right

<image>

You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move.

What is the minimum number of moves required to mow all the weeds?

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 150) — the number of rows and columns respectively. Then follow n lines containing m characters each — the content of the grid. "G" means that this cell contains grass. "W" means that this cell contains weeds.

It is guaranteed that the top-left corner of the grid will contain grass.

Output

Print a single number — the minimum number of moves required to mow all the weeds.

Examples

Input

4 5
GWGGW
GGWGG
GWGGG
WGGGG

Output

11

Input

3 3
GWW
WWW
WWG

Output

7

Input

1 1
G

Output

0

Note

For the first example, this is the picture of the initial state of the grid:

<image>

A possible solution is by mowing the weeds as illustrated below:

<image>

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

t = [(p.find('W'), p.rfind('W')) for p in [input() for i in range(n)]]

c, s, k = 0, n - 1, True

while s > 0 and t[s][0] == -1: s -= 1

for a, b in t[: s + 1]:

    if a != -1:

        if k:

            s += abs(a - c) + b - a

            c = b

        else:

            s += abs(b - c) + b - a

            c = a

    k = not k

print(s)

# Made By Mostafa_Khaled
```


1188_C. Array Beauty

Let's call beauty of an array b_1, b_2, …, b_n (n > 1) — min_{1 ≤ i < j ≤ n} |b_i - b_j|.

You're given an array a_1, a_2, … a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.

A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements.

Input

The first line contains integers n, k (2 ≤ k ≤ n ≤ 1000).

The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^5).

Output

Output one integer — the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.

Examples

Input

4 3
1 7 3 5

Output

8

Input

5 5
1 10 100 1000 10000

Output

9

Note

In the first example, there are 4 subsequences of length 3 — [1, 7, 3], [1, 3, 5], [7, 3, 5], [1, 7, 5], each of which has beauty 2, so answer is 8.

In the second example, there is only one subsequence of length 5 — the whole array, which has the beauty equal to |10-1| = 9.

```python
from collections import defaultdict
import sys
input = sys.stdin.readline
'''
for CASES in range(int(input())):
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
sys.stdout.write(" ".join(map(str,ans))+"\n")
'''
inf = 100000000000000000  # 1e17
mod = 998244353

n, m = map(int, input().split())
A = [0] + sorted(list(map(int, input().split())))

ans = 0

f = [[0] * (n + 10) for _ in range(m + 10)]

for x in range(1,(A[n] - A[1]) // (m - 1) + 1):
    for i in range(1, n + 1):
        f[1][i] = 1
    for i in range(2, m + 1):
        sum = 0
        pre = 1
        for j in range(1, n + 1):
            while pre <= n and A[pre] + x <= A[j]:
                sum += f[i - 1][pre]
                sum %= mod
                pre += 1
            f[i][j] = sum
    for i in range(1, n + 1):
        ans += f[m][i]
        ans %= mod
print(ans)

# the end

```


1207_D. Number Of Permutations

You are given a sequence of n pairs of integers: (a_1, b_1), (a_2, b_2), ... , (a_n, b_n). This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences:

  * s = [(1, 2), (3, 2), (3, 1)] is bad because the sequence of first elements is sorted: [1, 3, 3];
  * s = [(1, 2), (3, 2), (1, 2)] is bad because the sequence of second elements is sorted: [2, 2, 2];
  * s = [(1, 1), (2, 2), (3, 3)] is bad because both sequences (the sequence of first elements and the sequence of second elements) are sorted;
  * s = [(1, 3), (3, 3), (2, 2)] is good because neither the sequence of first elements ([1, 3, 2]) nor the sequence of second elements ([3, 3, 2]) is sorted.

Calculate the number of permutations of size n such that after applying this permutation to the sequence s it turns into a good sequence.

A permutation p of size n is a sequence p_1, p_2, ... , p_n consisting of n distinct integers from 1 to n (1 ≤ p_i ≤ n). If you apply permutation p_1, p_2, ... , p_n to the sequence s_1, s_2, ... , s_n you get the sequence s_{p_1}, s_{p_2}, ... , s_{p_n}. For example, if s = [(1, 2), (1, 3), (2, 3)] and p = [2, 3, 1] then s turns into [(1, 3), (2, 3), (1, 2)].

Input

The first line contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5).

The next n lines contains description of sequence s. The i-th line contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n) — the first and second elements of i-th pair in the sequence.

The sequence s may contain equal elements.

Output

Print the number of permutations of size n such that after applying this permutation to the sequence s it turns into a good sequence. Print the answer modulo 998244353 (a prime number).

Examples

Input

3
1 1
2 2
3 1

Output

3

Input

4
2 3
2 2
2 1
2 4

Output

0

Input

3
1 1
1 1
2 3

Output

4

Note

In first test case there are six permutations of size 3:

  1. if p = [1, 2, 3], then s = [(1, 1), (2, 2), (3, 1)] — bad sequence (sorted by first elements);
  2. if p = [1, 3, 2], then s = [(1, 1), (3, 1), (2, 2)] — bad sequence (sorted by second elements);
  3. if p = [2, 1, 3], then s = [(2, 2), (1, 1), (3, 1)] — good sequence;
  4. if p = [2, 3, 1], then s = [(2, 2), (3, 1), (1, 1)] — good sequence;
  5. if p = [3, 1, 2], then s = [(3, 1), (1, 1), (2, 2)] — bad sequence (sorted by second elements);
  6. if p = [3, 2, 1], then s = [(3, 1), (2, 2), (1, 1)] — good sequence.

```python
from collections import defaultdict
import math

MOD = 998244353

def facmod(n):
    fac = 1
    for i in range(2, n + 1):
        fac *= i
        fac %= MOD
    return fac

def main():
    n = int(input())
    s = [tuple(int(s) for s in input().split()) for _ in range(n)]

    count = defaultdict(int)

    for a, _ in s:
        count[a] += 1

    first = 1
    for c in count.values():
        first *= facmod(c)
        first %= MOD

    count = defaultdict(int)

    for _, b in s:
        count[b] += 1

    second = 1
    for c in count.values():
        second *= facmod(c)
        second %= MOD

    count = defaultdict(int)

    for t in s:
        count[t] += 1

    both = 1
    for c in count.values():
        both *= facmod(c)
        both %= MOD

    s.sort()

    for i, (_, b) in enumerate(s[:-1]):
        if b > s[i + 1][1]:
            both = 0
            break

    print((facmod(n) - (first + second - both)) % MOD)

if __name__ == '__main__':
    main()

```


1225_E. Rock Is Push

You are at the top left cell (1, 1) of an n × m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y).

Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on.

The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal.

Count the number of different legal paths you can take from the start to the goal modulo 10^9 + 7. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other.

Input

The first line contains two integers n, m — dimensions of the labyrinth (1 ≤ n, m ≤ 2000).

Next n lines describe the labyrinth. Each of these lines contains m characters. The j-th character of the i-th of these lines is equal to "R" if the cell (i, j) contains a rock, or "." if the cell (i, j) is empty.

It is guaranteed that the starting cell (1, 1) is empty.

Output

Print a single integer — the number of different legal paths from (1, 1) to (n, m) modulo 10^9 + 7.

Examples

Input

1 1
.

Output

1

Input

2 3
...
..R

Output

0

Input

4 4
...R
.RR.
.RR.
R...

Output

4

Note

In the first sample case we can't (and don't have to) move, hence the only path consists of a single cell (1, 1).

In the second sample case the goal is blocked and is unreachable.

Illustrations for the third sample case can be found here: <https://assets.codeforces.com/rounds/1225/index.html>

```python
def getSum(dp, pos, s, e, type_):
    if e < s:
        return 0

    if type_=='D':
        if e==m-1:
            return dp[pos][s]
        return dp[pos][s]-dp[pos][e+1]
    else:
        if e==n-1:
            return dp[s][pos]
        return dp[s][pos]-dp[e+1][pos]

mod  = 10**9+7
n, m = map(int, input().split())
a    = [list(list(map(lambda x: 1 if x=='R' else 0, input()))) for _ in range(n)]

SD  = [[0]*m for _ in range(n)]
SN  = [[0]*m for _ in range(n)]
dpD = [[0]*m for _ in range(n)]
dpN = [[0]*m for _ in range(n)]

for i in range(n-1, -1, -1):
    for j in range(m-1, -1, -1):
        if i == n-1:
            SD[i][j]=a[i][j]
        else:
            SD[i][j]=SD[i+1][j]+a[i][j]

        if j == m-1:
            SN[i][j]=a[i][j]
        else:
            SN[i][j]=SN[i][j+1]+a[i][j]

for j in range(m-1,-1,-1):
    if a[n-1][j]==1:
        break
    dpD[n-1][j]=1
    dpN[n-1][j]=1

for i in range(n-1,-1,-1):
    if a[i][m-1]==1:
        break
    dpD[i][m-1]=1
    dpN[i][m-1]=1

for j in range(m-2, -1, -1):
    if i==n-1:
        break
    dpD[n-1][j]+=dpD[n-1][j+1]

for i in range(n-2,-1,-1):
    if j==m-1:
        break
    dpN[i][m-1]+=dpN[i+1][m-1]

for i in range(n-2,-1,-1):
    for j in range(m-2,-1,-1):
        s, e = j, m-SN[i][j]-1
        #print(i, j, s, e, 'N')
        dpN[i][j]  = getSum(dpD, i+1, s, e, 'D')
        dpN[i][j]  = (dpN[i][j] + dpN[i+1][j]) % mod

        s, e = i, n-SD[i][j]-1
        #print(i, j, s, e, 'D')
        dpD[i][j]  = getSum(dpN, j+1, s, e, 'N')

    if i != 0:
        for j in range(m-2,-1,-1):
            dpD[i][j] = (dpD[i][j] + dpD[i][j+1]) % mod

print(dpD[0][0] % mod)
```


124_A. The number of positions

Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.

Input

The only line contains three integers n, a and b (0 ≤ a, b < n ≤ 100).

Output

Print the single number — the number of the sought positions.

Examples

Input

3 1 1

Output

2

Input

5 2 3

Output

3

Note

The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1).

In the second sample they are 3, 4 and 5.

```python
x,y,z=map(int,input().split())
if y+z>=x:
    print(x-y)
else:
    print(z+1)
```


1333_D. Challenges in school №41

There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.

Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.

You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.

For instance, for the configuration shown below and k = 2 children can do the following steps:

<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration:  <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job.  <image>

It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".

Input

The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.

The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.

Output

If there is no solution, print a single line with number -1.

Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.

After performing all "headturns", there can't be a pair of two neighboring children looking at each other.

If there are many solutions, print any of them.

Examples

Input

2 1
RL

Output

1 1

Input

2 1
LR

Output

-1

Input

4 2
RLRL

Output

2 1 3
1 2

Note

The first sample contains a pair of children who look at each other. After one move, they can finish the process.

In the second sample, children can't make any move. As a result, they can't end in k>0 moves.

The third configuration is described in the statement.

```python
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    n , k = [int(n) for n in input().split()]
    arr = input()
    max_moves = 0
    min_moves = 0

    movements = []

    while 'RL' in arr:
        min_moves+=1
        max_moves+= arr.count('RL')
        ref_arr = arr.replace('RL','LR')
        movements.append([i for i,(old,new) in enumerate(zip(arr,ref_arr),1) if old == 'R' and new == 'L'])
        arr = ref_arr

    if k>max_moves or k<min_moves:
        print(-1)
    else:
        movements=movements[::-1]
        while k:
            if k>len(movements):
                print(1,movements[-1].pop())
                if not movements[-1]:
                    movements.pop()
            else:
                print(len(movements[-1]), " ".join(str(x) for x in movements[-1]))
                movements.pop()
            k-=1

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

```


1354_A. Alarm Clock

Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed.

Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes.

Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than a minutes in total, then he sets his alarm to go off in c minutes after it is reset and spends d minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day.

If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another c minutes and tries to fall asleep for d minutes again.

You just want to find out when will Polycarp get out of his bed or report that it will never happen.

Please check out the notes for some explanations of the example.

Input

The first line contains one integer t (1 ≤ t ≤ 1000) — the number of testcases.

The only line of each testcase contains four integers a, b, c, d (1 ≤ a, b, c, d ≤ 10^9) — the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep.

Output

For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed.

Example

Input

7
10 3 6 4
11 3 6 4
5 9 4 10
6 5 2 3
1 1 1 1
3947465 47342 338129 123123
234123843 13 361451236 361451000

Output

27
27
9
-1
1
6471793
358578060125049

Note

In the first testcase Polycarp wakes up after 3 minutes. He only rested for 3 minutes out of 10 minutes he needed. So after that he sets his alarm to go off in 6 minutes and spends 4 minutes falling asleep. Thus, he rests for 2 more minutes, totaling in 3+2=5 minutes of sleep. Then he repeats the procedure three more times and ends up with 11 minutes of sleep. Finally, he gets out of his bed. He spent 3 minutes before the first alarm and then reset his alarm four times. The answer is 3+4 ⋅ 6 = 27.

The second example is almost like the first one but Polycarp needs 11 minutes of sleep instead of 10. However, that changes nothing because he gets 11 minutes with these alarm parameters anyway.

In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is b=9.

In the fourth testcase Polycarp wakes up after 5 minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(

```python
for i in range(int(input())):
    a,b,c,d=map(int,input().split())
    e=a-b
    if e<1:
        print(b)
        continue
    else:
        if c-d<1:
            print(-1)
            continue
        else:
            f=int(e//(c-d))
            if b+f*(c-d)>=a:
                print(b+f*c)
            else:
                print(b+(f+1)*c)

```


1373_F. Network Coverage

The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection.

The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city).

All network stations have capacities: the i-th station can provide the connection to at most b_i households.

Now the government asks you to check can the designed stations meet the needs of all cities or not — that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households.

Input

The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.

The first line of each test case contains the single integer n (2 ≤ n ≤ 10^6) — the number of cities and stations.

The second line of each test case contains n integers (1 ≤ a_i ≤ 10^9) — the number of households in the i-th city.

The third line of each test case contains n integers (1 ≤ b_i ≤ 10^9) — the capacities of the designed stations.

It's guaranteed that the sum of n over test cases doesn't exceed 10^6.

Output

For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive).

Example

Input

5
3
2 3 4
3 3 3
3
3 3 3
2 3 4
4
2 3 4 5
3 7 2 2
4
4 5 2 3
2 3 2 7
2
1 1
10 10

Output

YES
YES
NO
YES
YES

Note

In the first test case:

  * the first network station can provide 2 connections to the first city and 1 connection to the second city;
  * the second station can provide 2 connections to the second city and 1 connection to the third city;
  * the third station can provide 3 connections to the third city.

In the second test case:

  * the 1-st station can provide 2 connections to the 1-st city;
  * the 2-nd station can provide 3 connections to the 2-nd city;
  * the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station.

In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.

```python
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline

M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)

def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]

l1 = []
l2 = []
n = 0

def ispos(credit):
    # print(credit)
    global l1,l2,n
    l2[-1] -= credit
    curr = credit
    l2[0] -= max(0,l1[0] - credit)
    if l2[0] < 0:return 1

    for i in range(1,n):
        l2[i] -= max(0,l1[i] - l2[i-1])
        if l2[i] < 0:
            if i == n - 1:return -1
            else:return 1
    return 0

for _ in range(val()):
    n = val()
    l1 = li()
    l2 = li()
    orig1 = l1[:]
    orig2 = l2[:]

    ans = 0
    low = 0
    high = l2[-1]
    while low <= high:
        l1 = orig1[:]
        l2 = orig2[:]
        mid = (low + high) >> 1
        temp = ispos(mid)

        if not temp:
            ans = 1
            break
        elif temp == -1:
            high = mid - 1
        else:low = mid + 1
    print('YES' if ans else 'NO')

```


1420_B. Rock and Lever

"You must lift the dam. With a lever. I will give it to you.

You must block the canal. With a rock. I will not give the rock to you."

Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them.

Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task.

You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j ≥ a_i ⊕ a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).

Danik has solved this task. But can you solve it?

Input

Each test contains multiple test cases.

The first line contains one positive integer t (1 ≤ t ≤ 10) denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains one positive integer n (1 ≤ n ≤ 10^5) — length of the array.

The second line contains n positive integers a_i (1 ≤ a_i ≤ 10^9) — elements of the array.

It is guaranteed that the sum of n over all test cases does not exceed 10^5.

Output

For every test case print one non-negative integer — the answer to the problem.

Example

Input

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

Output

1
3
2
0
0

Note

In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 ⊕ 7 = 3.

In the second test case all pairs are good.

In the third test case there are two pairs: (6,5) and (2,3).

In the fourth test case there are no good pairs.

```python
def nCr(n, k):
	if k > n:
		return 0
	if(k > n - k):
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

for _ in range(int(input())):
    N = int(input())
    a = list(map(int, input().split()))

    d = {}

    for i in range(len(a)):
        a[i] = bin(a[i])[2:]

    for i in a:
        if len(i) not in d:
            d[len(i)] = 1
        else:
            d[len(i)] += 1

    count = 0

    for k, v in d.items():
        count += nCr(v, 2)

    print(count)

```


1439_A1. Binary Table (Easy Version)

This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.

You are given a binary table of size n × m. This table consists of symbols 0 and 1.

You can make such operation: select 3 different cells that belong to one 2 × 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).

Your task is to make all symbols in the table equal to 0. You are allowed to make at most 3nm operations. You don't need to minimize the number of operations.

It can be proved that it is always possible.

Input

The first line contains a single integer t (1 ≤ t ≤ 5000) — the number of test cases. The next lines contain descriptions of test cases.

The first line of the description of each test case contains two integers n, m (2 ≤ n, m ≤ 100).

Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.

It is guaranteed that the sum of nm for all test cases does not exceed 20000.

Output

For each test case print the integer k (0 ≤ k ≤ 3nm) — the number of operations.

In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, x_2, x_3 ≤ n, 1 ≤ y_1, y_2, y_3 ≤ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong into some 2 × 2 square.

Example

Input

5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101

Output

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

Note

In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.

In the second test case:

  * operation with cells (2, 1), (3, 1), (3, 2). After it the table will be:

    011
    001
    000

  * operation with cells (1, 2), (1, 3), (2, 3). After it the table will be:

    000
    000
    000

In the fifth test case:

  * operation with cells (1, 3), (2, 2), (2, 3). After it the table will be:

    010
    110

  * operation with cells (1, 2), (2, 1), (2, 2). After it the table will be:

    000
    000

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

def change(x1,x2,x3,y1,y2,y3,ll):
    ll[x1][y1]=1-ll[x1][y1]
    ll[x2][y2]=1-ll[x2][y2]
    #print(x3,y3,ll)
    ll[x3][y3]=1-ll[x3][y3]

t=int(input())
while t:
    n,m=map(int,input().split())
    ll=[]
    for i in range(n):
        l=list(map(int,input().strip()))
        ll.append(l)
    ans=[]
    #print(ll)
    for i in range(n-1):
        for j in range(m):
            if(i==n-2 and j==m-2):
                break
            if(ll[i][j]):
                #print("lol")
                if(j+1<m):
                    #print("lol")
                    ans.append((i+1,i+2,i+2,j+1,j+1,j+2))
                    #print(i+1,j+1,n,m)
                    change(i,i+1,i+1,j,j,j+1,ll)
                else:
                    ans.append((i+1,i+2,i+2,j+1,j+1,j))
                    change(i,i+1,i+1,j,j,j-1,ll)
    #print(ans,ll)
    for i in range(m-1):
        if(ll[n-1][i] and ll[n-2][i]):
            ans.append((n-1,n,n,i+1,i+1,i+2))
            change(n-2,n-1,n-1,i,i,i+1,ll)
        elif(ll[n-1][i]):
            ans.append((n,n,n-1,i+1,i+2,i+2))
            change(n-1,n-1,n-2,i,i+1,i+1,ll)
        elif(ll[n-2][i]):
            ans.append((n-1,n-1,n,i+1,i+2,i+2))
            change(n-2,n-2,n-1,i,i+1,i+1,ll)
    #for i in ll:
    #print(*i)
    #print(ans,ll)
    if(ll[n-1][m-1] and ll[n-2][m-1]):
        ans.append((n,n-1,n,m,m-1,m-1))
        ans.append((n,n-1,n-1,m-1,m-1,m))
    elif(ll[n-2][m-1]):
        #print("lol")
        ans.append((n-1,n,n,m,m,m-1))
        change(n-2,n-1,n-1,m-1,m-1,m-2,ll)
        #print()
        #for i in ll:
        #print(*i)

        ans.append((n,n-1,n-1,m,m-1,m))
        change(n-1,n-2,n-2,m-1,m-2,m-1,ll)
        #print()
        #for i in ll:
        #print(*i)
        ans.append((n,n-1,n-1,m-1,m,m-1))
        change(n-1,n-2,n-2,m-2,m-1,m-2,ll)
        #print()
        #for i in ll:
        #print(*i)
    elif(ll[n-1][m-1]):
        ans.append((n,n,n-1,m,m-1,m-1))
        ans.append((n-1,n-1,n,m-1,m,m))
        ans.append((n,n,n-1,m-1,m,m))
    print(len(ans))
    #for i in ll:
    #print(*i)
    for i in ans:
        x1,x2,x3,y1,y2,y3=i
        print(x1,y1,x2,y2,x3,y3)

    t-=1

```


1490_A. Dense Array

Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any i (1 ≤ i ≤ n-1), this condition must be satisfied: $$$(max(a[i], a[i+1]))/(min(a[i], a[i+1])) ≤ 2$$$

For example, the arrays [1, 2, 3, 4, 3], [1, 1, 1] and [5, 10] are dense. And the arrays [5, 11], [1, 4, 2], [6, 6, 1] are not dense.

You are given an array a of n integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.

For example, if a=[4,2,10,1], then the answer is 5, and the array itself after inserting elements into it may look like this: a=[4,2,\underline{3},\underline{5},10,\underline{6},\underline{4},\underline{2},1] (there are other ways to build such a).

Input

The first line contains one integer t (1 ≤ t ≤ 1000). Then t test cases follow.

The first line of each test case contains one integer n (2 ≤ n ≤ 50) — the length of the array a.

The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 50).

Output

For each test case, output one integer — the minimum number of numbers that must be added to the array to make it dense.

Example

Input

6
4
4 2 10 1
2
1 3
2
6 1
3
1 4 2
5
1 2 3 4 3
12
4 31 25 50 30 20 34 46 42 16 15 16

Output

5
1
2
1
0
3

Note

The first test case is explained in the statements.

In the second test case, you can insert one element, a=[1,\underline{2},3].

In the third test case, you can insert two elements, a=[6,\underline{4},\underline{2},1].

In the fourth test case, you can insert one element, a=[1,\underline{2},4,2].

In the fifth test case, the array a is already dense.

```python
for _ in range(int(input())):
    n=int(input())
    l=list(map(int,input().split()))
    s=0
    for i in range(n-1):
        a=max(l[i],l[i+1])
        b=min(l[i],l[i+1])
        while a>(2*b):
            s+=1
            b=b*2
    print(s)
```


1512_D. Corrupted Array

You are given a number n and an array b_1, b_2, …, b_{n+2}, obtained according to the following algorithm:

  * some array a_1, a_2, …, a_n was guessed;
  * array a was written to array b, i.e. b_i = a_i (1 ≤ i ≤ n);
  * The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. b_{n+1} = a_1+a_2+…+a_n;
  * The (n+2)-th element of the array b was written some number x (1 ≤ x ≤ 10^9), i.e. b_{n+2} = x; The
  * array b was shuffled.

For example, the array b=[2, 3, 7, 12 ,2] it could be obtained in the following ways:

  * a=[2, 2, 3] and x=12;
  * a=[3, 2, 7] and x=2.

For the given array b, find any array a that could have been guessed initially.

Input

The first line contains a single integer t (1 ≤ t ≤ 10^4). Then t test cases follow.

The first line of each test case contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).

The second row of each test case contains n+2 integers b_1, b_2, …, b_{n+2} (1 ≤ b_i ≤ 10^9).

It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.

Output

For each test case, output:

  * "-1", if the array b could not be obtained from any array a;
  * n integers a_1, a_2, …, a_n, otherwise.

If there are several arrays of a, you can output any.

Example

Input

4
3
2 3 7 12 2
4
9 1 7 1 6 5
5
18 2 2 3 2 9 2
3
2 6 9 2 1

Output

2 3 7
-1
2 2 2 3 9
1 2 6

```python
for _ in range(int(input())):
    n = int(input())
    a = sorted(list(map(int,input().split())))
    ans = [0]*(n+2)
    ans[0] = a[0]
    for i in range(1,n+2):
        ans[i] = ans[i-1] + a[i]
    #print(ans)
    j = -1
    for i in range(n+2):
        if n + 1 != i:
            if a[n+1] == ans[n] - a[i]:
                j = i
                break
        else:
            if ans[n] == 2 * ans[n-1]:
                j = i
                break
    if j == -1:
        print(j)
    else:
        if n + 1 != j:
            pp = n + 1
        else:
            pp = n
        k = [a[i] for i in range(pp) if i!=j]
        print(*k)

"""
4
3
2 3 7 12 2
4
9 1 7 1 6 5
5
18 2 2 3 2 9 2
3
2 6 9 2 1
"""

```


166_E. Tetrahedron

You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.

<image>

An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.

You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).

Input

The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.

Output

Print the only integer — the required number of ways modulo 1000000007 (109 + 7).

Examples

Input

2

Output

3

Input

4

Output

21

Note

The required paths in the first sample are:

  * D - A - D
  * D - B - D
  * D - C - D

```python
def fast_exp_pow(num, pw, mod):
	num %= mod
	if pw == 1:
		return num
	evener = 1
	if pw % 2 == 1:
		evener = num
	return (evener * (fast_exp_pow(num, pw // 2, mod) % mod) ** 2) % mod

mod = 1000000007
n = int(input())
if n == 1:
	print(0)
	quit()
x = ((fast_exp_pow(3, n - 1, mod) + (-1) ** (n & 1) + mod) * 3) % mod
y = 250000002
print((x * y) % mod)

```


208_D. Prizes, Prizes, more Prizes

Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.

Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.

The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):

  * a mug (costs a points),
  * a towel (costs b points),
  * a bag (costs c points),
  * a bicycle (costs d points),
  * a car (costs e points).

Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

Input

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Output

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed.

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

Examples

Input

3
3 10 4
2 4 10 15 20

Output

1 1 1 0 0
1

Input

4
10 4 39 2
3 5 10 11 12

Output

3 0 1 0 3
0

Note

In the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

```python
import bisect

n = int(input())
a = [int(x) for x in input().split()]
p = [int(x) for x in input().split()]
b = [0, 0, 0, 0, 0]
s = 0
for i in a:
    s += i
    k = bisect.bisect_right(p, s)
    while k != 0:
        if (k == 5) or (p[k] > s):
            k -= 1
        b[k] += s // p[k]
        s %= p[k]
        k = bisect.bisect_right(p, s)
print(' '.join(list(map(str, b))))
print(s)

```


25_A. IQ test

Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.

Input

The first line contains integer n (3 ≤ n ≤ 100) — amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.

Output

Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.

Examples

Input

5
2 4 7 8 10

Output

3

Input

4
1 2 1 1

Output

2

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

eve,eve_indx,neg,neg_indx=0,0,0,0

for i in range(n):
    x=q[i]%2
    if x==0:
        eve +=1
        eve_indx=i
    else:
        neg +=1
        neg_indx=i

if eve==1:
    print(eve_indx+1)
else:
    print(neg_indx+1)
```


283_A. Cows and Sequence

Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:

  1. Add the integer xi to the first ai elements of the sequence.
  2. Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1)
  3. Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence.

After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!

Input

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≤ ti ≤ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≤ 103; 1 ≤ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≤ 103). If ti = 3, it will not be followed by anything.

It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.

Output

Output n lines each containing the average of the numbers in the sequence after the corresponding operation.

The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

Examples

Input

5
2 1
3
2 3
2 1
3

Output

0.500000
0.000000
1.500000
1.333333
1.500000

Input

6
2 1
1 2 20
2 2
1 2 -3
3
3

Output

0.500000
20.500000
14.333333
12.333333
17.500000
17.000000

Note

In the second sample, the sequence becomes <image>

```python
from sys import stdin
input = stdin.readline
n = int(input())
arr, cnt, curr_len, curr_sum = [0] * (n+1), [0] * (n+1), 1, 0
for _ in range(n):
    s = input()
    if s[0] == '1':
        _, x, y = map(int, s.split())
        curr_sum += x*y
        cnt[x-1] += y
    elif s[0] == '2':
        _, x = map(int, s.split())
        curr_sum += x
        arr[curr_len] = x
        curr_len += 1
    else:
        curr_len -= 1
        curr_sum -= arr[curr_len] + cnt[curr_len]
        cnt[curr_len-1] += cnt[curr_len]
        cnt[curr_len] = 0
    print('%.9f' % (curr_sum / curr_len))

```


305_E. Playing with String

Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses.

Before the game began, the string is written on a piece of paper, one letter per cell.

<image> An example of the initial situation at s = "abacaba"

A player's move is the sequence of actions:

  1. The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available.
  2. The player chooses in the string t = t1t2... t|t| character in position i (1 ≤ i ≤ |t|) such that for some positive integer l (0 < i - l; i + l ≤ |t|) the following equations hold: ti - 1 = ti + 1, ti - 2 = ti + 2, ..., ti - l = ti + l.
  3. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti - 1, the second one will contain a string consisting of a single character ti, the third one contains string ti + 1ti + 2... t|t|.

<image> An example of making action (i = 4) with string s = «abacaba»

Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.

Input

The first line contains string s (1 ≤ |s| ≤ 5000). It is guaranteed that string s only contains lowercase English letters.

Output

If the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move — integer i (1 ≤ i ≤ |s|).

Examples

Input

abacaba

Output

First
2

Input

abcde

Output

Second

Note

In the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2.

In the second sample the first player has no available moves.

```python
U = input()
memo = {}

DP = [0]*(len(U)+1)
DP[0] = 0
for j in range(1, len(U) + 1):
    s = set()
    for i in range(j):
        s.add(DP[max(0, i - 1)] ^ DP[max(0, j - i - 2)])
    mex = 0
    while mex in s:
        mex += 1
    DP[j] = mex

memo2 = {}

def Grundy(S):
    """
    Basically we transform the game.
    From a game where we can pick only center of palindrom to a game with several pile where we can pick anything (but it removes adjacent stone)
    In this new game, only the remaining size matters (since we can pick anywhere)
    """
    if S in memo2: return memo2[S]
    total = 0
    consec = 0
    for i in range(1, len(S) - 1):
        if S[i - 1] == S[i + 1]:
            consec += 1
        else:
            total ^= DP[consec]
            consec = 0
    total ^= DP[consec]
    memo2[S] = total
    return total

import sys

sys.setrecursionlimit(3000)

if (Grundy(U) != 0):
    #print(Grundy(U))
    for i in range(1, len(U) - 1):
        if U[i - 1] == U[i + 1]:
            if ((Grundy(U[:i]) ^ Grundy(U[i + 1:])) == 0):
                print("First")
                print(i + 1)
                break
else:
    print("Second")
```


331_C2. The Great Julya Calendar

Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar.

The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows:

"May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"

Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.

Input

The single line contains the magic integer n, 0 ≤ n.

  * to get 20 points, you need to solve the problem with constraints: n ≤ 106 (subproblem C1);
  * to get 40 points, you need to solve the problem with constraints: n ≤ 1012 (subproblems C1+C2);
  * to get 100 points, you need to solve the problem with constraints: n ≤ 1018 (subproblems C1+C2+C3).

Output

Print a single integer — the minimum number of subtractions that turns the magic number to a zero.

Examples

Input

24

Output

5

Note

In the first test sample the minimum number of operations can be reached by the following sequence of subtractions:

24 → 20 → 18 → 10 → 9 → 0


353_D. Queue

There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.

Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.

Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.

Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.

Input

The first line contains a sequence of letters without spaces s1s2... sn (1 ≤ n ≤ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.

Output

Print a single integer — the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.

Examples

Input

MFM

Output

1

Input

MMFF

Output

3

Input

FFMMM

Output

0

Note

In the first test case the sequence of changes looks as follows: MFM →  FMM.

The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF →  MFMF →  FMFM →  FFMM.

```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq,bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1

class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n

# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default=2**51, func=lambda a, b: a & b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: max(a , b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)

# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]

class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m

# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z

# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por

# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left) / 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid] <=key):
            count = mid + 1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count

# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c
def binary(x, length):
    y = bin(x)[2:]
    return y if len(y) >= length else "0" * (length - len(y)) + y

def countGreater(arr, n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)

# --------------------------------------------------binary------------------------------------
s=list(input())
st=0
for i in range(len(s)-1,-1,-1):
    if s[i]=='F':
        st=i
        break
if st==0:
    print(0)
    sys.exit(0)
c=0
f=[]
m=[]
if s[st-1]=='M':
    f.append(0)
for i in range(st-1,-1,-1):
    if s[i]=='M':
        if c!=0:
            f.append(c)
        c=0
    else:
        c+=1
if c!=0:
    f.append(c)
c=0
for i in range(st-1,-1,-1):
    if s[i]=='F':
        if c!=0:
            m.append(c)
        c=0
    else:
        c+=1
if c!=0:
    m.append(c)
if len(f)>len(m):
    f=f[:len(f)-1]
ans=0
back=0
fcur=0
for i in range(len(f)):
    fcur+=f[i]
    cur=max(0,fcur-back)+m[i]
    ans+=cur
    back=back+cur
print(ans)

```


39_B. Company Income Growth

Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 — to a2 billion, ..., and in the current (2000 + n)-th year — an billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year — 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers ai can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers ai from the sequence and leave only some subsequence that has perfect growth.

Thus Petya has to choose a sequence of years y1, y2, ..., yk,so that in the year y1 the company income amounted to 1 billion bourles, in the year y2 — 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.

Input

The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers ai ( - 100 ≤ ai ≤ 100). The number ai determines the income of BerSoft company in the (2000 + i)-th year. The numbers in the line are separated by spaces.

Output

Output k — the maximum possible length of a perfect sequence. In the next line output the sequence of years y1, y2, ..., yk. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.

Examples

Input

10
-2 1 1 3 2 3 4 -10 -2 5

Output

5
2002 2005 2006 2007 2010

Input

3
-1 -2 -3

Output

0

```python
_, values,i,years = int(input()),[int(i) for i in input().split(" ")],1,[]
if 1 in values:
	years.append(values.index(1))
	i=2
	while i in values[years[-1]:]:
		years.append(values[years[-1]:].index(i)+years[-1])
		i+=1
print(len(years))
if len(years) !=0:
	for year in years:
		print(2001+year,end=" ")
	print()
```


424_C. Magic Formulas

People in the Tomskaya region like magic formulas very much. You can see some of them below.

Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas:

<image><image>

Here, "mod" means the operation of taking the residue after dividing.

The expression <image> means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal — by "xor".

People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q.

Input

The first line of the input contains the only integer n (1 ≤ n ≤ 106). The next line contains n integers: p1, p2, ..., pn (0 ≤ pi ≤ 2·109).

Output

The only line of output should contain a single integer — the value of Q.

Examples

Input

3
1 2 3

Output

3

```python
import sys
input=sys.stdin.readline
n=int(input())
ar=list(map(int,input().split()))
dp=[0]
pre=0
for i in range(1,n+1):
    pre^=i
    dp.append(pre)
ans=0
for i in range(1,n+1):
    xx=ar[i-1]^(dp[i-1]*((n//i)%2))^(dp[n%i])
    ans^=xx
print(ans)
```


449_A. Jzzhu and Chocolate

Jzzhu has a big rectangular chocolate bar that consists of n × m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements:

  * each cut should be straight (horizontal or vertical);
  * each cut should go along edges of unit squares (it is prohibited to divide any unit chocolate square with cut);
  * each cut should go inside the whole chocolate bar, and all cuts must be distinct.

The picture below shows a possible way to cut a 5 × 6 chocolate for 5 times.

<image>

Imagine Jzzhu have made k cuts and the big chocolate is splitted into several pieces. Consider the smallest (by area) piece of the chocolate, Jzzhu wants this piece to be as large as possible. What is the maximum possible area of smallest piece he can get with exactly k cuts? The area of a chocolate piece is the number of unit squares in it.

Input

A single line contains three integers n, m, k (1 ≤ n, m ≤ 109; 1 ≤ k ≤ 2·109).

Output

Output a single integer representing the answer. If it is impossible to cut the big chocolate k times, print -1.

Examples

Input

3 4 1

Output

6

Input

6 4 2

Output

8

Input

2 3 4

Output

-1

Note

In the first sample, Jzzhu can cut the chocolate following the picture below:

<image>

In the second sample the optimal division looks like this:

<image>

In the third sample, it's impossible to cut a 2 × 3 chocolate 4 times.

```python
l = input().split()
n = int(l[0])
m = int(l[1])
k = int(l[2])

if ( k <= n+m-2 ):
    if ( k < n ):
        outn = int((n / (k + 1))) * m
    else:
        outn = int(m / (k - n + 2))
    if ( k < m):
        outm = int( m / ( k + 1)) * n
    else:
        outm = int( n / ( k - m + 2 ))
    print ("", max( outn, outm), sep = '')
else:
    print ( "-1")
```