1066_A. Vova and Train

Vova plans to go to the conference by train. Initially, the train is at the point 1 and the destination point of the path is the point L. The speed of the train is 1 length unit per minute (i.e. at the first minute the train is at the point 1, at the second minute — at the point 2 and so on).

There are lanterns on the path. They are placed at the points with coordinates divisible by v (i.e. the first lantern is at the point v, the second is at the point 2v and so on).

There is also exactly one standing train which occupies all the points from l to r inclusive.

Vova can see the lantern at the point p if p is divisible by v and there is no standing train at this position (p not∈ [l; r]). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.

Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to t different conferences, so you should answer t independent queries.

Input

The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of queries.

Then t lines follow. The i-th line contains four integers L_i, v_i, l_i, r_i (1 ≤ L, v ≤ 10^9, 1 ≤ l ≤ r ≤ L) — destination point of the i-th path, the period of the lantern appearance and the segment occupied by the standing train.

Output

Print t lines. The i-th line should contain one integer — the answer for the i-th query.

Example

Input

4
10 2 3 7
100 51 51 51
1234 1 100 199
1000000000 1 1 1000000000

Output

3
0
1134
0

Note

For the first example query, the answer is 3. There are lanterns at positions 2, 4, 6, 8 and 10, but Vova didn't see the lanterns at positions 4 and 6 because of the standing train.

For the second example query, the answer is 0 because the only lantern is at the point 51 and there is also a standing train at this point.

For the third example query, the answer is 1134 because there are 1234 lanterns, but Vova didn't see the lanterns from the position 100 to the position 199 inclusive.

For the fourth example query, the answer is 0 because the standing train covers the whole path.

```python

if __name__ == '__main__':
    t = input()
    t = int(t)
    while t:
        e, v, l, r = input().split()
        e = int(e)
        v = int(v)
        l = int(l)
        r = int(r)
        res = e//v
        if l % v != 0:
            st = l//v + 1
        else:
            st = l//v
        en = r//v
        print(res-(en-st+1))
        t=t-1

```


1107_F. Vasya and Endless Credits

Vasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles.

However, the local bank has n credit offers. Each offer can be described with three numbers a_i, b_i and k_i. Offers are numbered from 1 to n. If Vasya takes the i-th offer, then the bank gives him a_i burles at the beginning of the month and then Vasya pays bank b_i burles at the end of each month for the next k_i months (including the month he activated the offer). Vasya can take the offers any order he wants.

Each month Vasya can take no more than one credit offer. Also each credit offer can not be used more than once. Several credits can be active at the same time. It implies that Vasya pays bank the sum of b_i over all the i of active credits at the end of each month.

Vasya wants to buy a car in the middle of some month. He just takes all the money he currently has and buys the car of that exact price.

Vasya don't really care what he'll have to pay the bank back after he buys a car. He just goes out of the country on his car so that the bank can't find him anymore.

What is the maximum price that car can have?

Input

The first line contains one integer n (1 ≤ n ≤ 500) — the number of credit offers.

Each of the next n lines contains three integers a_i, b_i and k_i (1 ≤ a_i, b_i, k_i ≤ 10^9).

Output

Print one integer — the maximum price of the car.

Examples

Input

4
10 9 2
20 33 1
30 115 1
5 3 2

Output

32

Input

3
40 1 2
1000 1100 5
300 2 1

Output

1337

Note

In the first example, the following sequence of offers taken is optimal: 4 → 3.

The amount of burles Vasya has changes the following way: 5 → 32 → -86 → .... He takes the money he has in the middle of the second month (32 burles) and buys the car.

The negative amount of money means that Vasya has to pay the bank that amount of burles.

In the second example, the following sequence of offers taken is optimal: 3 → 1 → 2.

The amount of burles Vasya has changes the following way: 0 → 300 → 338 → 1337 → 236 → -866 → ....

```python
n = int(input())
a = [tuple(map(int, input().split())) for i in range(n)]

a = [(y, x, k) for x, y, k in a]
a.sort(reverse=True)
dp = [[-1] * (n + 1) for i in range(n)]

def f(i, j):
    if i < 0 or j < -1: return 0
    if dp[i][j] == -1:
        y, x, k = a[i]
        dp[i][j] = f(i - 1, j) + max(0, x - k * y)
        if 0 <= j < k: dp[i][j] = max(dp[i][j], x - j * y + f(i - 1, j - 1))
    return dp[i][j]

print(max(f(n - 1, j) for j in range(-1, n)))

```


1137_A. Skyscrapers

Dora loves adventures quite a lot. During some journey she encountered an amazing city, which is formed by n streets along the Eastern direction and m streets across the Southern direction. Naturally, this city has nm intersections. At any intersection of i-th Eastern street and j-th Southern street there is a monumental skyscraper. Dora instantly became curious and decided to explore the heights of the city buildings.

When Dora passes through the intersection of the i-th Eastern and j-th Southern street she examines those two streets. After Dora learns the heights of all the skyscrapers on those two streets she wonders: how one should reassign heights to the skyscrapers on those two streets, so that the maximum height would be as small as possible and the result of comparing the heights of any two skyscrapers on one street wouldn't change.

Formally, on every of nm intersections Dora solves an independent problem. She sees n + m - 1 skyscrapers and for each of them she knows its real height. Moreover, any two heights can be compared to get a result "greater", "smaller" or "equal". Now Dora wants to select some integer x and assign every skyscraper a height from 1 to x. When assigning heights, Dora wants to preserve the relative order of the skyscrapers in both streets. That is, the result of any comparison of heights of two skyscrapers in the current Eastern street shouldn't change and the result of any comparison of heights of two skyscrapers in current Southern street shouldn't change as well. Note that skyscrapers located on the Southern street are not compared with skyscrapers located on the Eastern street only. However, the skyscraper located at the streets intersection can be compared with both Southern and Eastern skyscrapers. For every intersection Dora wants to independently calculate the minimum possible x.

For example, if the intersection and the two streets corresponding to it look as follows:

<image>

Then it is optimal to replace the heights of the skyscrapers as follows (note that all comparisons "less", "equal", "greater" inside the Eastern street and inside the Southern street are preserved)

<image>

The largest used number is 5, hence the answer for this intersection would be 5.

Help Dora to compute the answers for each intersection.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of streets going in the Eastern direction and the number of the streets going in Southern direction.

Each of the following n lines contains m integers a_{i,1}, a_{i,2}, ..., a_{i,m} (1 ≤ a_{i,j} ≤ 10^9). The integer a_{i,j}, located on j-th position in the i-th line denotes the height of the skyscraper at the intersection of the i-th Eastern street and j-th Southern direction.

Output

Print n lines containing m integers each. The integer x_{i,j}, located on j-th position inside the i-th line is an answer for the problem at the intersection of i-th Eastern street and j-th Southern street.

Examples

Input

2 3
1 2 1
2 1 2

Output

2 2 2
2 2 2

Input

2 2
1 2
3 4

Output

2 3
3 2

Note

In the first example, it's not possible to decrease the maximum used height for the problem at any intersection, hence we don't have to change any heights.

In the second example, the answers are as follows:

  * For the intersection of the first line and the first column <image>
  * For the intersection of the first line and the second column <image>
  * For the intersection of the second line and the first column <image>
  * For the intersection of the second line and the second column <image>

```python
import sys
input=sys.stdin.buffer.readline
from bisect import bisect_left
n,m=map(int,input().split())
arr=[]
for i in range(n):
    arr.append(list(map(int,input().split())))
arr_maxi=[[0 for i in range(m)] for j in range(n)]
arr_mini=[[0 for i in range(m)] for j in range(n)]
for i in range(n):
    s=sorted(set(arr[i]))
    for j in range(m):
        indx=bisect_left(s,arr[i][j])
        arr_maxi[i][j]=len(s)-indx-1
        arr_mini[i][j]=indx
for j in range(m):
    s=sorted(set([arr[i][j] for i in range(n)]))
    for i in range(n):
        indx=bisect_left(s,arr[i][j])
        arr_maxi[i][j]=max(arr_maxi[i][j],len(s)-indx-1)
        arr_mini[i][j] = max(arr_mini[i][j], indx)
for i in range(n):
    for j in range(m):
        print(arr_maxi[i][j] +arr_mini[i][j] +1,end=' ')
    print()
```


1155_C. Alarm Clocks Everywhere

Ivan is going to sleep now and wants to set his alarm clock. There will be many necessary events tomorrow, the i-th of them will start during the x_i-th minute. Ivan doesn't want to skip any of the events, so he has to set his alarm clock in such a way that it rings during minutes x_1, x_2, ..., x_n, so he will be awake during each of these minutes (note that it does not matter if his alarm clock will ring during any other minute).

Ivan can choose two properties for the alarm clock — the first minute it will ring (let's denote it as y) and the interval between two consecutive signals (let's denote it by p). After the clock is set, it will ring during minutes y, y + p, y + 2p, y + 3p and so on.

Ivan can choose any minute as the first one, but he cannot choose any arbitrary value of p. He has to pick it among the given values p_1, p_2, ..., p_m (his phone does not support any other options for this setting).

So Ivan has to choose the first minute y when the alarm clock should start ringing and the interval between two consecutive signals p_j in such a way that it will ring during all given minutes x_1, x_2, ..., x_n (and it does not matter if his alarm clock will ring in any other minutes).

Your task is to tell the first minute y and the index j such that if Ivan sets his alarm clock with properties y and p_j it will ring during all given minutes x_1, x_2, ..., x_n or say that it is impossible to choose such values of the given properties. If there are multiple answers, you can print any.

Input

The first line of the input contains two integers n and m (2 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ m ≤ 3 ⋅ 10^5) — the number of events and the number of possible settings for the interval between signals.

The second line of the input contains n integers x_1, x_2, ..., x_n (1 ≤ x_i ≤ 10^{18}), where x_i is the minute when i-th event starts. It is guaranteed that all x_i are given in increasing order (i. e. the condition x_1 < x_2 < ... < x_n holds).

The third line of the input contains m integers p_1, p_2, ..., p_m (1 ≤ p_j ≤ 10^{18}), where p_j is the j-th option for the interval between two consecutive signals.

Output

If it's impossible to choose such values y and j so all constraints are satisfied, print "NO" in the first line.

Otherwise print "YES" in the first line. Then print two integers y (1 ≤ y ≤ 10^{18}) and j (1 ≤ j ≤ m) in the second line, where y is the first minute Ivan's alarm clock should start ringing and j is the index of the option for the interval between two consecutive signals (options are numbered from 1 to m in the order they are given input). These values should be chosen in such a way that the alarm clock will ring during all given minutes x_1, x_2, ..., x_n. If there are multiple answers, you can print any.

Examples

Input

3 5
3 12 18
2 6 5 3 3

Output

YES
3 4

Input

4 2
1 5 17 19
4 5

Output

NO

Input

4 2
1 5 17 19
2 1

Output

YES
1 1

```python
def gcd(a,b):
    if b==0:
        return a
    else:
        return gcd(b,a%b)

n, m = map(int, input().split(' '))
x = list(map(int, input().split(' ')))
p = list(map(int, input().split(' ')))
dx = [x[i+1]-x[i] for i in range(n-1)]
d = dx[0]
for i in dx:
    d = gcd(i, d)
for i in range(m):
    if d % p[i] == 0:
        print('YES')
        print(x[0], i+1)
        exit()
print('NO')
```


1177_B. Digits Sequence (Hard Edition)

Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536...

Your task is to print the k-th digit of this sequence.

Input

The first and only line contains integer k (1 ≤ k ≤ 10^{12}) — the position to process (1-based index).

Output

Print the k-th digit of the resulting infinite sequence.

Examples

Input

7

Output

7

Input

21

Output

5

```python
#import sys
#digit = int(sys.argv[1])
digit = int(input())

if int(digit) <= 9:
    print(digit)
    exit()

start_range = 1
end_range = 9

power = 1
digit_count = 2
while not (start_range <= digit and digit <= end_range):
    start_range = end_range + 1
    end_range = 9 * 10**power * digit_count + start_range - 1
    power += 1
    digit_count += 1

offset_number = (digit - start_range) // (digit_count - 1)
#print(f"{digit} - {start_range} mod {digit_count-1} = {offset_number}")
number = str(10**(power - 1) + offset_number)
#print(f"10^ {power - 1} + {offset_number} = {number}")
offset_digit = (digit - start_range) % (digit_count - 1)
#print(f"{digit} - {start_range} mod {digit_count - 1 } = {offset_digit}")
#print(f"{number} {number[-offset_digit]}")
print(f"{number[offset_digit]}")

```


1213_B. Bad Prices

Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i.

Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if n=6 and a=[3, 9, 4, 6, 7, 5], then the number of days with a bad price is 3 — these are days 2 (a_2=9), 4 (a_4=6) and 5 (a_5=7).

Print the number of days with a bad price.

You have to answer t independent data sets.

Input

The first line contains an integer t (1 ≤ t ≤ 10000) — the number of sets of input data in the test. Input data sets must be processed independently, one after another.

Each input data set consists of two lines. The first line contains an integer n (1 ≤ n ≤ 150000) — the number of days. The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^6), where a_i is the price on the i-th day.

It is guaranteed that the sum of n over all data sets in the test does not exceed 150000.

Output

Print t integers, the j-th of which should be equal to the number of days with a bad price in the j-th input data set.

Example

Input

5
6
3 9 4 6 7 5
1
1000000
2
2 1
10
31 41 59 26 53 58 97 93 23 84
7
3 2 1 2 3 4 5

Output

3
0
1
8
2

```python
for _ in range(int(input())):
    n = int(input())
    lst = list(map(int, input().split()))
    cnt = 0
    x = lst[-1]
    for i in lst[:-1][::-1]:
        x = min((x, i))
        if x < i:
            cnt += 1
    print(cnt)

```


1236_C. Labs

In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, …, the lab with the number n^2 is at the highest place.

To transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number u to the lab with the number v if u > v.

Now the labs need to be divided into n groups, each group should contain exactly n labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group A to a group B is equal to the number of pairs of labs (u, v) such that the lab with the number u is from the group A, the lab with the number v is from the group B and u > v. Let's denote this value as f(A,B) (i.e. f(A,B) is the sum of units of water that can be sent from a group A to a group B).

For example, if n=3 and there are 3 groups X, Y and Z: X = \{1, 5, 6\}, Y = \{2, 4, 9\} and Z = \{3, 7, 8\}. In this case, the values of f are equal to:

  * f(X,Y)=4 because of 5 → 2, 5 → 4, 6 → 2, 6 → 4,
  * f(X,Z)=2 because of 5 → 3, 6 → 3,
  * f(Y,X)=5 because of 2 → 1, 4 → 1, 9 → 1, 9 → 5, 9 → 6,
  * f(Y,Z)=4 because of 4 → 3, 9 → 3, 9 → 7, 9 → 8,
  * f(Z,X)=7 because of 3 → 1, 7 → 1, 7 → 5, 7 → 6, 8 → 1, 8 → 5, 8 → 6,
  * f(Z,Y)=5 because of 3 → 2, 7 → 2, 7 → 4, 8 → 2, 8 → 4.

Please, divide labs into n groups with size n, such that the value min f(A,B) over all possible pairs of groups A and B (A ≠ B) is maximal.

In other words, divide labs into n groups with size n, such that minimum number of the sum of units of water that can be transported from a group A to a group B for every pair of different groups A and B (A ≠ B) as big as possible.

Note, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values f for some division.

If there are many optimal divisions, you can find any.

Input

The only line contains one number n (2 ≤ n ≤ 300).

Output

Output n lines:

In the i-th line print n numbers, the numbers of labs of the i-th group, in any order you want.

If there are multiple answers, that maximize the minimum number of the sum of units of water that can be transported from one group the another, you can print any.

Example

Input

3

Output

2 8 5
9 3 4
7 6 1

Note

In the first test we can divide 9 labs into groups \{2, 8, 5\}, \{9, 3, 4\}, \{7, 6, 1\}.

From the first group to the second group we can transport 4 units of water (8 → 3, 8 → 4, 5 → 3, 5 → 4).

From the first group to the third group we can transport 5 units of water (2 → 1, 8 → 7, 8 → 6, 8 → 1, 5 → 1).

From the second group to the first group we can transport 5 units of water (9 → 2, 9 → 8, 9 → 5, 3 → 2, 4 → 2).

From the second group to the third group we can transport 5 units of water (9 → 7, 9 → 6, 9 → 1, 3 → 1, 4 → 1).

From the third group to the first group we can transport 4 units of water (7 → 2, 7 → 5, 6 → 2, 6 → 5).

From the third group to the second group we can transport 4 units of water (7 → 3, 7 → 4, 6 → 3, 6 → 4).

The minimal number of the sum of units of water, that can be transported from one group to another is equal to 4. It can be proved, that it is impossible to make a better division.

```python
n = int(input())
a = [[] for i in range(n)]
j = 0
k = 1

cnt = 0
for i in range(n):
    for j in range(n):
        cnt += 1
        if (i % 2 == 0):
            a[j].append(cnt)
        else:
            a[-j-1].append(cnt)

for i in range(n):
    print(*a[i])
```


1254_B1. Send Boxes to Alice (Easy Version)

This is the easier version of the problem. In this version, 1 ≤ n ≤ 10^5 and 0 ≤ a_i ≤ 1. You can hack this problem only if you solve and lock both problems.

Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces.

Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, …, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k > 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes.

Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

Input

The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of chocolate boxes.

The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 1) — the number of chocolate pieces in the i-th box.

It is guaranteed that at least one of a_1, a_2, …, a_n is positive.

Output

If there is no way for Charlie to make Alice happy, print -1.

Otherwise, print a single integer x — the minimum number of seconds for Charlie to help Bob make Alice happy.

Examples

Input

3
1 0 1

Output

2

Input

1
1

Output

-1

```python
from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from time import time
from itertools import permutations as per
from heapq import heapify,heappush,heappop,heappushpop
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\r\n')
L=lambda:list(R())
P=lambda x:stdout.write(str(x)+'\n')
lcm=lambda x,y:(x*y)//gcd(x,y)
nCr=lambda x,y:(f[x]*inv((f[y]*f[x-y])%N))%N
inv=lambda x:pow(x,N-2,N)
sm=lambda x:(x**2+x)//2
N=10**9+7

def get_ans(x):
	ans=0
	for i in range(p):
		#print(i+(x-(i+1)%x)%x-x//2)
		ans+=abs(ind[i+(x-(i+1)%x)%x-x//2]-ind[i])
	return ans

n=I()
a=L()
p=cnt=a.count(1)
if cnt==1:exit(print(-1))
ans=inf
ind=[i for i in range(n) if a[i]]
for i in range(2,int(sqrt(cnt))+1):
	if not cnt%i:
		ans=min(ans,get_ans(i))
		while not cnt%i:
			cnt//=i
if cnt!=1:ans=min(ans,get_ans(cnt))
print(ans)
```


1278_A. Shuffle Hashing

Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.

Polycarp decided to store the hash of the password, generated by the following algorithm:

  1. take the password p, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain p' (p' can still be equal to p);
  2. generate two random strings, consisting of lowercase Latin letters, s_1 and s_2 (any of these strings can be empty);
  3. the resulting hash h = s_1 + p' + s_2, where addition is string concatenation.

For example, let the password p = "abacaba". Then p' can be equal to "aabcaab". Random strings s1 = "zyx" and s2 = "kjh". Then h = "zyxaabcaabkjh".

Note that no letters could be deleted or added to p to obtain p', only the order could be changed.

Now Polycarp asks you to help him to implement the password check module. Given the password p and the hash h, check that h can be the hash for the password p.

Your program should answer t independent test cases.

Input

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

The first line of each test case contains a non-empty string p, consisting of lowercase Latin letters. The length of p does not exceed 100.

The second line of each test case contains a non-empty string h, consisting of lowercase Latin letters. The length of h does not exceed 100.

Output

For each test case print the answer to it — "YES" if the given hash h could be obtained from the given password p or "NO" otherwise.

Example

Input

5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten

Output

YES
YES
NO
YES
NO

Note

The first test case is explained in the statement.

In the second test case both s_1 and s_2 are empty and p'= "threetwoone" is p shuffled.

In the third test case the hash could not be obtained from the password.

In the fourth test case s_1= "n", s_2 is empty and p'= "one" is p shuffled (even thought it stayed the same).

In the fifth test case the hash could not be obtained from the password.

```python
t = int(input())
for _ in range(t):
	s = input()
	t = input()
	ok = False
	s = ''.join(sorted(s))
	for i in range(len(t) - len(s) + 1):
		temp = ''.join(sorted(t[i:i+len(s)]))
		if temp == s:
			ok = True
			break
	if ok:
		print("YES")
	else:
		print("NO")

```


1321_B. Journey Planning

Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n.

Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, ..., c_k] should be strictly increasing.

There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold.

For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey:

  * c = [1, 2, 4];
  * c = [3, 5, 6, 8];
  * c = [7] (a journey consisting of one city is also valid).

There are some additional ways to plan a journey that are not listed above.

Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?

Input

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

The second line contains n integers b_1, b_2, ..., b_n (1 ≤ b_i ≤ 4 ⋅ 10^5), where b_i is the beauty value of the i-th city.

Output

Print one integer — the maximum beauty of a journey Tanya can choose.

Examples

Input

6
10 7 1 9 10 15

Output

26

Input

1
400000

Output

400000

Input

7
8 9 26 11 12 29 14

Output

55

Note

The optimal journey plan in the first example is c = [2, 4, 5].

The optimal journey plan in the second example is c = [1].

The optimal journey plan in the third example is c = [3, 6].

```python
from sys import stdin, gettrace

if not gettrace():
    def input():
        return next(stdin)[:-1]

def main():
    n = int(input())
    bb = [int(a) for a in input().split()]
    seq = {}
    for i, b in enumerate(bb):
        if b - i in seq:
            seq[b-i] += b
        else:
            seq[b-i] = b
    print(max(seq.values()))

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


1340_A. Nastya and Strange Generator

Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something.

Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.

When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of n steps. At the i-th step, a place is chosen for the number i (1 ≤ i ≤ n). The position for the number i is defined as follows:

  * For all j from 1 to n, we calculate r_j — the minimum index such that j ≤ r_j ≤ n, and the position r_j is not yet occupied in the permutation. If there are no such positions, then we assume that the value of r_j is not defined.
  * For all t from 1 to n, we calculate count_t — the number of positions 1 ≤ j ≤ n such that r_j is defined and r_j = t.
  * Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the count array is maximum.
  * The generator selects one of these positions for the number i. The generator can choose any position.

Let's have a look at the operation of the algorithm in the following example:

<image>

Let n = 5 and the algorithm has already arranged the numbers 1, 2, 3 in the permutation. Consider how the generator will choose a position for the number 4:

  * The values of r will be r = [3, 3, 3, 4, ×], where × means an indefinite value.
  * Then the count values will be count = [0, 0, 3, 1, 0].
  * There are only two unoccupied positions in the permutation: 3 and 4. The value in the count array for position 3 is 3, for position 4 it is 1.
  * The maximum value is reached only for position 3, so the algorithm will uniquely select this position for number 4.

Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind p_1, p_2, …, p_n and decided to find out if it could be obtained as a result of the generator.

Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.

Input

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

The first line of the test case contains a single integer n (1 ≤ n ≤ 10^5) — the size of the permutation.

The second line of the test case contains n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n) — the permutation written by Denis.

It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.

Output

Print "Yes" if this permutation could be obtained as a result of the generator. Otherwise, print "No".

All letters can be displayed in any case.

Example

Input

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

Output

Yes
Yes
No
Yes
No

Note

Let's simulate the operation of the generator in the first test.

At the 1 step, r = [1, 2, 3, 4, 5], count = [1, 1, 1, 1, 1]. The maximum value is reached in any free position, so the generator can choose a random position from 1 to 5. In our example, it chose 5.

At the 2 step, r = [1, 2, 3, 4, ×], count = [1, 1, 1, 1, 0]. The maximum value is reached in positions from 1 to 4, so the generator can choose a random position among them. In our example, it chose 1.

At the 3 step, r = [2, 2, 3, 4, ×], count = [0, 2, 1, 1, 0]. The maximum value is 2 and is reached only at the 2 position, so the generator will choose this position.

At the 4 step, r = [3, 3, 3, 4, ×], count = [0, 0, 3, 1, 0]. The maximum value is 3 and is reached only at the 3 position, so the generator will choose this position.

At the 5 step, r = [4, 4, 4, 4, ×], count = [0, 0, 0, 4, 0]. The maximum value is 4 and is reached only at the 4 position, so the generator will choose this position.

In total, we got a permutation of 2, 3, 4, 5, 1, that is, a generator could generate it.

```python
t=int(input())
for pp in range(0,t):
    n=int(input())
    arr=list(map(int,input().split()))
    arr.append(-1)
    pt1=0
    pt2=0
    while(pt1!=n):
        ele=arr[pt1]
        if(ele==-1):
            break
        for i in range(pt1+1,n+1):
            if(arr[i]-ele==1):
                pt2=i
                ele=arr[i]
            else:
                for j in range(pt1,pt2+1):
                    arr[j]=ele
                break
        pt1=pt2+1
        pt2=pt1
    ip=[]
    dct={}
    for i in arr:
        if(i!=-1):
            if i not in dct:
                ip.append(i)
                dct[i]=1
    pi=[]
    for i in ip:
        pi.append(i)
    pi.sort(reverse=True)
    if(pi==ip):
        print("Yes")
    else:
        print("No")
```


1362_A. Johnny and Ancient Computer

Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can multiply or divide your number by 2, 4 or 8, and division is only allowed if the number is divisible by the chosen divisor.

Formally, if the register contains a positive integer x, in one operation it can be replaced by one of the following:

  * x ⋅ 2
  * x ⋅ 4
  * x ⋅ 8
  * x / 2, if x is divisible by 2
  * x / 4, if x is divisible by 4
  * x / 8, if x is divisible by 8

For example, if x = 6, in one operation it can be replaced by 12, 24, 48 or 3. Value 6 isn't divisible by 4 or 8, so there're only four variants of replacement.

Now Johnny wonders how many operations he needs to perform if he puts a in the register and wants to get b at the end.

Input

The input consists of multiple test cases. The first line contains an integer t (1 ≤ t ≤ 1000) — the number of test cases. The following t lines contain a description of test cases.

The first and only line in each test case contains integers a and b (1 ≤ a, b ≤ 10^{18}) — the initial and target value of the variable, respectively.

Output

Output t lines, each line should contain one integer denoting the minimum number of operations Johnny needs to perform. If Johnny cannot get b at the end, then write -1.

Example

Input

10
10 5
11 44
17 21
1 1
96 3
2 128
1001 1100611139403776
1000000000000000000 1000000000000000000
7 1
10 8

Output

1
1
-1
0
2
2
14
0
-1
-1

Note

In the first test case, Johnny can reach 5 from 10 by using the shift to the right by one (i.e. divide by 2).

In the second test case, Johnny can reach 44 from 11 by using the shift to the left by two (i.e. multiply by 4).

In the third test case, it is impossible for Johnny to reach 21 from 17.

In the fourth test case, initial and target values are equal, so Johnny has to do 0 operations.

In the fifth test case, Johnny can reach 3 from 96 by using two shifts to the right: one by 2, and another by 3 (i.e. divide by 4 and by 8).

```python
# from debug import debug
import math
t = int(input())

for ii in range(t):
	a, b = map(int, input().split())
	if a == b:
		print(0)
	else:
		b, a = min(a,b), max(a,b)
		if a%b:
			print(-1)
		else:
			aa = int(math.log2(a//b))
			if pow(2, aa) == a//b:
				c = 0
				c += aa//3
				aa = aa%3

				c += aa//2
				aa = aa%2

				c += aa//1
				aa = aa%1
				print(c)
			else:
				print(-1)

```


1382_C1. Prefix Flip (Easy Version)

This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.

There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In an operation, you select a prefix of a, and simultaneously invert the bits in the prefix (0 changes to 1 and 1 changes to 0) and reverse the order of the bits in the prefix.

For example, if a=001011 and you select the prefix of length 3, it becomes 011011. Then if you select the entire string, it becomes 001001.

Your task is to transform the string a into b in at most 3n operations. It can be proved that it is always possible.

Input

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

The first line of each test case contains a single integer n (1≤ n≤ 1000) — the length of the binary strings.

The next two lines contain two binary strings a and b of length n.

It is guaranteed that the sum of n across all test cases does not exceed 1000.

Output

For each test case, output an integer k (0≤ k≤ 3n), followed by k integers p_1,…,p_k (1≤ p_i≤ n). Here k is the number of operations you use and p_i is the length of the prefix you flip in the i-th operation.

Example

Input

5
2
01
10
5
01011
11100
2
01
01
10
0110011011
1000110100
1
0
1

Output

3 1 2 1
6 5 2 5 3 1 2
0
9 4 1 2 10 4 1 2 1 5
1 1

Note

In the first test case, we have 01→ 11→ 00→ 10.

In the second test case, we have 01011→ 00101→ 11101→ 01000→ 10100→ 00100→ 11100.

In the third test case, the strings are already the same. Another solution is to flip the prefix of length 2, which will leave a unchanged.

```python
from collections import defaultdict as dd
import sys
input=sys.stdin.readline
t=int(input())
while t:
    n=int(input())
    #d=dd(int)
    #n,m=map(int,input().split())
    #l=list(map(int,input().split()))
    a=list(map(int,input().strip()))
    b=list(map(int,input().strip()))
    j=n-1
    ans=[]
    while j>=0:
        #print(j,a)
        while j>=0 and  b[j]==a[j]:
            j-=1
        if(j>=0 and a[0]==b[j]):
            a[0]=1-a[0]
            ans.append(1)
        if(j%2==1):
            k=j//2+1
        else:
            k=j//2
            if(j>=0 and j%2==0):
                a[j//2]=1-a[j//2]
        for i in range(k):
            a[i],a[j-i]=1-a[j-i],1-a[i]

        if(j>=0):
            ans.append(j+1)
        j-=1
    #print(a)
    print(len(ans),*ans)
    t-=1

```


1471_A. Strange Partition

You are given an array a of length n, and an integer x. You can perform the following operation as many times as you would like (possibly zero): replace two adjacent elements of the array by their sum. For example, if the initial array was [3, 6, 9], in a single operation one can replace the last two elements by their sum, yielding an array [3, 15], or replace the first two elements to get an array [9, 9]. Note that the size of the array decreases after each operation.

The beauty of an array b=[b_1, …, b_k] is defined as ∑_{i=1}^k \left⌈ (b_i)/(x) \right⌉, which means that we divide each element by x, round it up to the nearest integer, and sum up the resulting values. For example, if x = 3, and the array is [4, 11, 6], the beauty of the array is equal to \left⌈ 4/3 \right⌉ + \left⌈ 11/3 \right⌉ + \left⌈ 6/3 \right⌉ = 2 + 4 + 2 = 8.

Please determine the minimum and the maximum beauty you can get by performing some operations on the original array.

Input

The first input line contains a single integer t — the number of test cases (1 ≤ t ≤ 1000).

The first line of each test case contains two integers n and x (1 ≤ n ≤ 10^5, 1 ≤ x ≤ 10^9).

The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), the elements of the array a.

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

Output

For each test case output two integers — the minimal and the maximal possible beauty.

Example

Input

2
3 3
3 6 9
3 3
6 4 11

Output

6 6
7 8

Note

In the first test case the beauty of the array does not change if we perform any operations.

In the second example we can leave the array unchanged to attain the maximum beauty, and to get the minimum beauty one can replace two elements 4 and 11 with their sum, yielding an array [6, 15], which has its beauty equal to 7.

```python
from math import ceil
t = int(input())
for _ in range(t):
    n,x = map(int,input().split())
    a = list(map(int,input().split()))
    mx = 0
    mn = 0
    for y in a:
        mx += ceil(y/x)
        mn += y
    mn = ceil(mn/x)
    print(mn,mx)
```


1498_A. GCD Sum

The \text{gcdSum} of a positive integer is the gcd of that integer with its sum of digits. Formally, \text{gcdSum}(x) = gcd(x,  sum of digits of  x) for a positive integer x. gcd(a, b) denotes the greatest common divisor of a and b — the largest integer d such that both integers a and b are divisible by d.

For example: \text{gcdSum}(762) = gcd(762, 7 + 6 + 2)=gcd(762,15) = 3.

Given an integer n, find the smallest integer x ≥ n such that \text{gcdSum}(x) > 1.

Input

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

Then t lines follow, each containing a single integer n (1 ≤ n ≤ 10^{18}).

All test cases in one test are different.

Output

Output t lines, where the i-th line is a single integer containing the answer to the i-th test case.

Example

Input

3
11
31
75

Output

12
33
75

Note

Let us explain the three test cases in the sample.

Test case 1: n = 11:

\text{gcdSum}(11) = gcd(11, 1 + 1) = gcd(11,\ 2) = 1.

\text{gcdSum}(12) = gcd(12, 1 + 2) = gcd(12,\ 3) = 3.

So the smallest number ≥ 11 whose gcdSum > 1 is 12.

Test case 2: n = 31:

\text{gcdSum}(31) = gcd(31, 3 + 1) = gcd(31,\ 4) = 1.

\text{gcdSum}(32) = gcd(32, 3 + 2) = gcd(32,\ 5) = 1.

\text{gcdSum}(33) = gcd(33, 3 + 3) = gcd(33,\ 6) = 3.

So the smallest number ≥ 31 whose gcdSum > 1 is 33.

Test case 3: \ n = 75:

\text{gcdSum}(75) = gcd(75, 7 + 5) = gcd(75,\ 12) = 3.

The \text{gcdSum} of 75 is already > 1. Hence, it is the answer.

```python
def gcd(a,b):

    # Everything divides 0
    if (b == 0):
         return a
    return gcd(b, a%b)

for i in range(int(input())):
    n=int(input())
    while(True):
        l=list(str(n))
        sum1=0
        for i in l:
            sum1+=int(i)

        if(gcd(n,sum1)>1):
            print(n)
            break
        n+=1
```


1547_E. Air Conditioners

On a strip of land of length n there are k air conditioners: the i-th air conditioner is placed in cell a_i (1 ≤ a_i ≤ n). Two or more air conditioners cannot be placed in the same cell (i.e. all a_i are distinct).

Each air conditioner is characterized by one parameter: temperature. The i-th air conditioner is set to the temperature t_i.

<image> Example of strip of length n=6, where k=2, a=[2,5] and t=[14,16].

For each cell i (1 ≤ i ≤ n) find it's temperature, that can be calculated by the formula $$$min_{1 ≤ j ≤ k}(t_j + |a_j - i|),$$$

where |a_j - i| denotes absolute value of the difference a_j - i.

In other words, the temperature in cell i is equal to the minimum among the temperatures of air conditioners, increased by the distance from it to the cell i.

Let's look at an example. Consider that n=6, k=2, the first air conditioner is placed in cell a_1=2 and is set to the temperature t_1=14 and the second air conditioner is placed in cell a_2=5 and is set to the temperature t_2=16. In that case temperatures in cells are:

  1. temperature in cell 1 is: min(14 + |2 - 1|, 16 + |5 - 1|)=min(14 + 1, 16 + 4)=min(15, 20)=15;
  2. temperature in cell 2 is: min(14 + |2 - 2|, 16 + |5 - 2|)=min(14 + 0, 16 + 3)=min(14, 19)=14;
  3. temperature in cell 3 is: min(14 + |2 - 3|, 16 + |5 - 3|)=min(14 + 1, 16 + 2)=min(15, 18)=15;
  4. temperature in cell 4 is: min(14 + |2 - 4|, 16 + |5 - 4|)=min(14 + 2, 16 + 1)=min(16, 17)=16;
  5. temperature in cell 5 is: min(14 + |2 - 5|, 16 + |5 - 5|)=min(14 + 3, 16 + 0)=min(17, 16)=16;
  6. temperature in cell 6 is: min(14 + |2 - 6|, 16 + |5 - 6|)=min(14 + 4, 16 + 1)=min(18, 17)=17.

For each cell from 1 to n find the temperature in it.

Input

The first line contains one integer q (1 ≤ q ≤ 10^4) — the number of test cases in the input. Then test cases follow. Before each test case, there is an empty line.

Each test case contains three lines. The first line contains two integers n (1 ≤ n ≤ 3 ⋅ 10^5) and k (1 ≤ k ≤ n) — the length of the strip of land and the number of air conditioners respectively.

The second line contains k integers a_1, a_2, …, a_k (1 ≤ a_i ≤ n) — positions of air conditioners on the strip of land.

The third line contains k integers t_1, t_2, …, t_k (1 ≤ t_i ≤ 10^9) — temperatures of air conditioners.

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

Output

For each test case output n integers separated by space: temperatures of air in cells.

Example

Input

5

6 2
2 5
14 16

10 1
7
30

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

7 1
1
1000000000

6 3
6 1 3
5 5 5

Output

15 14 15 16 16 17
36 35 34 33 32 31 30 31 32 33
1 2 3 4 5
1000000000 1000000001 1000000002 1000000003 1000000004 1000000005 1000000006
5 6 5 6 6 5

```python
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def msi(): return map(str,input().split())
def li(): return list(mi())

t=ii()
for _ in range(t):
    s=si()
    n,k=mi()
    a=li()
    temp=li()
    ac=[]
    for i in range(k):
        ac.append([a[i],temp[i]])

    ac.sort()
    btemp=temp.copy()
    ldp,rdp=[0]*n,[0]*n
    dp=[0]*n
    #a.sort()
    b=ac.copy()
    ind=0;bind=k-1
    mini=10**11;maxi=10**11
    for i in range(n):
        if ind<k:
            if i+1==ac[ind][0]:
                if ac[ind][1]-ac[ind][0]<mini:
                    mini=ac[ind][1]-ac[ind][0]

                ind+=1
                #ac.pop(0)
                #temp.pop(0)

                ldp[i]=mini+i+1

            else:
                ldp[i]=mini+i+1

        else:
            ldp[i]=mini+i+1

    for i in range(n-1,-1,-1):
        if bind>-1:
            if i+1==b[bind][0]:
                if b[bind][1]+b[bind][0]<maxi:
                    maxi=b[bind][1]+b[bind][0]

                bind-=1
                #b.pop()
                #btemp.pop()

                rdp[i]=maxi-i-1

            else:
                rdp[i]=maxi-i-1

        else:
            rdp[i]=maxi-i-1

    for i in range(n):
        dp[i]=min(ldp[i],rdp[i])

    print(*dp)

```


175_B. Plane of Tanks: Pro

Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results.

A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.

In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:

  * "noob" — if more than 50% of players have better results;
  * "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results;
  * "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results;
  * "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results;
  * "pro" — if his result is not worse than the result that 99% of players have.

When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.

Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.

Input

The first line contains the only integer number n (1 ≤ n ≤ 1000) — a number of records with the players' results.

Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.

Output

Print on the first line the number m — the number of players, who participated in one round at least.

Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.

Examples

Input

5
vasya 100
vasya 200
artem 100
kolya 200
igor 250

Output

4
artem noob
igor pro
kolya random
vasya random

Input

3
vasya 200
kolya 1000
vasya 1000

Output

2
kolya pro
vasya pro

Note

In the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro".

In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".

```python
from collections import defaultdict
from bisect import bisect_left
p, n = defaultdict(int), int(input())
for i in range(n):
    a, b = input().split()
    p[a] = max(p[a], int(b))
p, n = sorted((b, a) for a, b in p.items()), len(p)
t = [0] + [bisect_left(p, (p[n - 1 - n // k][0], '')) for k in [2, 5, 10, 100]] + [n]
s = ['noob', 'random', 'average', 'hardcore', 'pro']
for i in range(1, len(t)):
    d = s[i - 1]
    for j in range(t[i - 1], t[i]): p[j] = p[j][1] + ' ' + d
print(n)
print('\n'.join(p))
```


195_C. Try and Catch

Vasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.

The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks:

  1. The try operator. It opens a new try-catch-block.
  2. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.

The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.

Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".

To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.

Your task is: given a program in VPL, determine, what message will be displayed on the screen.

Input

The first line contains a single integer: n (1 ≤ n ≤ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces.

The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark.

The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols.

Length of any line in the input file does not exceed 50 symbols.

Output

Print the message the screen will show after the given program is executed.

Examples

Input

8
try
    try
        throw ( AE )
    catch ( BE, "BE in line 3")

    try
    catch(AE, "AE in line 5")
catch(AE,"AE somewhere")

Output

AE somewhere

Input

8
try
    try
        throw ( AE )
    catch ( AE, "AE in line 3")

    try
    catch(BE, "BE in line 5")
catch(AE,"AE somewhere")

Output

AE in line 3

Input

8
try
    try
        throw ( CE )
    catch ( BE, "BE in line 3")

    try
    catch(AE, "AE in line 5")
catch(AE,"AE somewhere")

Output

Unhandled Exception

Note

In the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.

In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")

In the third sample there is no blocks that can be activated by an exception of type CE.

```python
import sys
import math

MAXNUM = math.inf
MINNUM = -1 * math.inf
ASCIILOWER = 97
ASCIIUPPER = 65

def getInt():
    return int(sys.stdin.readline().rstrip())

def getInts():
    return map(int, sys.stdin.readline().rstrip().split(" "))

def getString():
    return sys.stdin.readline().rstrip()

def printOutput(ans):
    sys.stdout.write()
    pass

def solve(parsedprog):
    stack = []
    for op in parsedprog:
        # print(stack)
        # print(op)
        if op and op[0] in ("try", "throw"):
            stack.append(op)
        elif op and op[0] == "catch":
            k = stack.pop()
            if k[0] == "throw":
                if op[1] == k[1]:
                    return op[2]
                else:
                    stack.append(k)

    return "Unhandled Exception"

def multisplit(string):
    """splits at a bracket, comma, quote, or text"""
    """does not split within quotes."""
    parsedstring = []
    curstring = []
    insidequotes = False
    for i in string:

        if insidequotes:
            if i == '"':
                insidequotes = False
                parsedstring.append("".join(curstring))
                curstring = []
            else:
                curstring.append(i)

        elif i in ("(", ")", ",", " "):
            if curstring:
                parsedstring.append("".join(curstring))
            curstring = []

        elif i == '"':
            insidequotes = True
            if curstring:
                parsedstring.append("".join(curstring))
            curstring = []

        else:
            curstring.append(i)

    if curstring:
        parsedstring.append("".join(curstring))
    return parsedstring

def readinput():
    proglen = getInt()
    parsedprog = []
    for _ in range(proglen):
        parsedprog.append(multisplit(getString()))
    print(solve(parsedprog))

readinput()

```


219_C. Color Stripe

A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.

Input

The first input line contains two integers n and k (1 ≤ n ≤ 5·105; 2 ≤ k ≤ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.

Output

Print a single integer — the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.

Examples

Input

6 3
ABBACC

Output

2
ABCACA

Input

3 2
BBB

Output

1
BAB

```python
n,k=map(int,input().split())
s=input()
if(k==2):
    #A
    sol1=[s[i] for i in range(n)]
    ans1=0
    for i in range(n):
        if(i%2==0 and sol1[i]=="B"):
            ans1+=1
            sol1[i]="A"
        elif(i%2!=0 and sol1[i]=="A"):
            ans1+=1
            sol1[i]="B"
    #B
    sol2=[s[i] for i in range(n)]
    ans2=0
    for i in range(n):
        if(i%2==0 and sol2[i]=="A"):
            ans2+=1
            sol2[i]="B"
        elif(i%2!=0 and sol2[i]=="B"):
            ans2+=1
            sol2[i]="A"
    if(ans1<=ans2):
        print(ans1)
        print("".join(str(x) for x in sol1))
    else:
        print(ans2)
        print("".join(str(x) for x in sol2))
else:
    s=[s[i] for i in range(n)]
    ans=0
    for i in range(1,n):
        if(s[i]==s[i-1]):
            ans+=1
            x=chr((ord(s[i-1])-65+1)%k+65)
            if(i==n-1 or s[i+1]!=x):s[i]=x
            else:
                y=chr((ord(s[i-1])-65+1+1)%k+65)
                s[i]=y
    print(ans)
    print("".join(str(x) for x in s))
```


268_C. Beautiful Sets of Points

Manao has invented a new mathematical term — a beautiful set of points. He calls a set of points on a plane beautiful if it meets the following conditions:

  1. The coordinates of each point in the set are integers.
  2. For any two points from the set, the distance between them is a non-integer.

Consider all points (x, y) which satisfy the inequations: 0 ≤ x ≤ n; 0 ≤ y ≤ m; x + y > 0. Choose their subset of maximum size such that it is also a beautiful set of points.

Input

The single line contains two space-separated integers n and m (1 ≤ n, m ≤ 100).

Output

In the first line print a single integer — the size k of the found beautiful set. In each of the next k lines print a pair of space-separated integers — the x- and y- coordinates, respectively, of a point from the set.

If there are several optimal solutions, you may print any of them.

Examples

Input

2 2

Output

3
0 1
1 2
2 0

Input

4 3

Output

4
0 3
2 1
3 0
4 2

Note

Consider the first sample. The distance between points (0, 1) and (1, 2) equals <image>, between (0, 1) and (2, 0) — <image>, between (1, 2) and (2, 0) — <image>. Thus, these points form a beautiful set. You cannot form a beautiful set with more than three points out of the given points. Note that this is not the only solution.

```python
if __name__ == '__main__':

    nums = input().split()
    n = int(nums[0])
    m = int(nums[1])

    k = min(m, n) + 1
    print(k)
    for i in range(k):
        print(str(i) + " " + str(k-1-i))
```


339_C. Xenia and Weights

Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.

Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≤ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.

You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on the scales or to say that it can't be done.

Input

The first line contains a string consisting of exactly ten zeroes and ones: the i-th (i ≥ 1) character in the line equals "1" if Xenia has i kilo weights, otherwise the character equals "0". The second line contains integer m (1 ≤ m ≤ 1000).

Output

In the first line print "YES", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put m weights on the scales, then print in the next line m integers — the weights' weights in the order you put them on the scales.

If there are multiple solutions, you can print any of them.

Examples

Input

0000000101
3

Output

YES
8 10 8

Input

1000000000
2

Output

NO

```python
__author__ = 'ratnesh.mishra'

weights = map(int, input())

weights = [cnt for cnt, x in enumerate(weights, 1) if x]

m = int(input())

state = [(0, 0, 0, [])]

res = "NO"
while state:
    w, b, k, l = state.pop()

    if k == m:
        res = 'YES\n' + ' '.join(map(str, l))
        break

    for wt in weights:
        if wt != w and wt > b:
            state.append((wt, wt-b, k+1, l+[wt]))

print(res)

```


385_C. Bear and Prime Numbers

Recently, the bear started studying data structures and faced the following problem.

You are given a sequence of integers x1, x2, ..., xn of length n and m queries, each of them is characterized by two integers li, ri. Let's introduce f(p) to represent the number of such indexes k, that xk is divisible by p. The answer to the query li, ri is the sum: <image>, where S(li, ri) is a set of prime numbers from segment [li, ri] (both borders are included in the segment).

Help the bear cope with the problem.

Input

The first line contains integer n (1 ≤ n ≤ 106). The second line contains n integers x1, x2, ..., xn (2 ≤ xi ≤ 107). The numbers are not necessarily distinct.

The third line contains integer m (1 ≤ m ≤ 50000). Each of the following m lines contains a pair of space-separated integers, li and ri (2 ≤ li ≤ ri ≤ 2·109) — the numbers that characterize the current query.

Output

Print m integers — the answers to the queries on the order the queries appear in the input.

Examples

Input

6
5 5 7 10 14 15
3
2 11
3 12
4 4

Output

9
7
0

Input

7
2 3 5 7 11 4 8
2
8 10
2 123

Output

0
7

Note

Consider the first sample. Overall, the first sample has 3 queries.

  1. The first query l = 2, r = 11 comes. You need to count f(2) + f(3) + f(5) + f(7) + f(11) = 2 + 1 + 4 + 2 + 0 = 9.
  2. The second query comes l = 3, r = 12. You need to count f(3) + f(5) + f(7) + f(11) = 1 + 4 + 2 + 0 = 7.
  3. The third query comes l = 4, r = 4. As this interval has no prime numbers, then the sum equals 0.

```python
import math, sys

input = sys.stdin.buffer.readline

def ints():
    return map(int, input().split())

n = int(input())
x = list(ints())
MAX = max(x) + 1
freq = [0] * MAX
for i in x:
    freq[i] += 1

sieve = [False] * MAX
f = [0] * MAX
for i in range(2, MAX):
    if sieve[i]:
        continue
    for j in range(i, MAX, i):
        sieve[j] = True
        f[i] += freq[j]
for i in range(2, MAX):
    f[i] += f[i-1]

m = int(input())
for i in range(m):
    l, r = ints()
    if l >= MAX:
        print(0)
    elif r >= MAX:
        print(f[-1] - f[l-1])
    else:
        print(f[r] - f[l-1])
```


406_B. Toy Sum

Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.

There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds:

<image> "Are you kidding me?", asks Chris.

For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7.

<image>

However, now Chris has exactly s = 106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!

Input

The first line of input contains a single integer n (1 ≤ n ≤ 5·105), the number of blocks in the set X. The next line contains n distinct space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 106), the numbers of the blocks in X.

Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Output

In the first line of output print a single integer m (1 ≤ m ≤ 106 - n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y1, y2, ..., ym (1 ≤ yi ≤ 106), such that the required equality holds. The sets X and Y should not intersect, i.e. xi ≠ yj for all i, j (1 ≤ i ≤ n; 1 ≤ j ≤ m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.

Examples

Input

3
1 4 5

Output

2
999993 1000000

Input

1
1

Output

1
1000000

```python
import sys
INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

"""
Facts and Data representation
Constructive? Top bottom up down
"""
n, = I()
a = I()
M = 10 ** 6 + 1
take = [0] * M
for i in a:
  take[i] = 1

ans = []
ok = []
cnt = 0
for i in range(1, M // 2 + 1):
  if take[i] and take[M - i]:
    cnt += 1
  elif not take[i] and not take[M - i]:
    ok.append((i, M - i))
  elif take[i]:
    ans.append(M - i)
  else:
    ans.append(i)

for i in range(cnt):
  ans.append(ok[i][0])
  ans.append(ok[i][1])

print(len(ans))
print(*ans)
```


433_C. Ryouko's Memory Note

Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.

Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.

Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is <image>.

Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.

Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.

Input

The first line of input contains two integers n and m (1 ≤ n, m ≤ 105).

The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≤ ai ≤ n).

Output

Print a single integer — the minimum number of pages Ryouko needs to turn.

Examples

Input

4 6
1 2 3 4 3 2

Output

3

Input

10 5
9 4 3 8 8

Output

6

Note

In the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3.

In the second sample, optimal solution is achieved by merging page 9 to 4.

```python
def median(a):
    if len(a) == 0:
        return 0
    if len(a) % 2 == 1:
        return a[len(a) // 2]
    else:
        return (a[len(a) // 2] + a[(len(a) // 2) - 1]) // 2

def profit(a, old_val):
    a.sort()
    med = median(a)
    sum_old = 0
    sum_new = 0
    for i in a:
        sum_old += abs(i - old_val)
        sum_new += abs(i - med)
    return sum_old - sum_new

n, m = [int(c) for c in input().split()]
pages = [int(c) for c in input().split()]

count = {pages[0]: []}
current_page_switches = 0

for i in range(1, len(pages)):
    cur_i = pages[i]
    prev_i = pages[i - 1]
    if not(cur_i in count):
        count[cur_i] = []

    if cur_i != prev_i:
        count[cur_i].append(prev_i)
        count[prev_i].append(cur_i)
        current_page_switches += abs(cur_i - prev_i)

max_profit = 0

for i in count:
    if len(count[i]) > 0:
        tmp = profit(count[i], i)
        if tmp > max_profit:
            max_profit = tmp

print(current_page_switches - max_profit)

```


478_C. Table Decorations

You have r red, g green and b blue balloons. To decorate a single table for the banquet you need exactly three balloons. Three balloons attached to some table shouldn't have the same color. What maximum number t of tables can be decorated if we know number of balloons of each color?

Your task is to write a program that for given values r, g and b will find the maximum number t of tables, that can be decorated in the required manner.

Input

The single line contains three integers r, g and b (0 ≤ r, g, b ≤ 2·109) — the number of red, green and blue baloons respectively. The numbers are separated by exactly one space.

Output

Print a single integer t — the maximum number of tables that can be decorated in the required manner.

Examples

Input

5 4 3

Output

4

Input

1 1 1

Output

1

Input

2 3 3

Output

2

Note

In the first sample you can decorate the tables with the following balloon sets: "rgg", "gbb", "brr", "rrg", where "r", "g" and "b" represent the red, green and blue balls, respectively.

```python
a = sorted(list(map(int, input().split())))
a[2] = min(a[2], 2 * (a[0] + a[1]))
print(sum(a) // 3)

```


500_E. New Year Domino

Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos

User ainta, who lives in a 2D world, is going to post a video as well.

There are n dominoes on a 2D Cartesian plane. i-th domino (1 ≤ i ≤ n) can be represented as a line segment which is parallel to the y-axis and whose length is li. The lower point of the domino is on the x-axis. Let's denote the x-coordinate of the i-th domino as pi. Dominoes are placed one after another, so p1 < p2 < ... < pn - 1 < pn holds.

User ainta wants to take a video of falling dominoes. To make dominoes fall, he can push a single domino to the right. Then, the domino will fall down drawing a circle-shaped orbit until the line segment totally overlaps with the x-axis.

<image>

Also, if the s-th domino touches the t-th domino while falling down, the t-th domino will also fall down towards the right, following the same procedure above. Domino s touches domino t if and only if the segment representing s and t intersects.

<image>

See the picture above. If he pushes the leftmost domino to the right, it falls down, touching dominoes (A), (B) and (C). As a result, dominoes (A), (B), (C) will also fall towards the right. However, domino (D) won't be affected by pushing the leftmost domino, but eventually it will fall because it is touched by domino (C) for the first time.

<image>

The picture above is an example of falling dominoes. Each red circle denotes a touch of two dominoes.

User ainta has q plans of posting the video. j-th of them starts with pushing the xj-th domino, and lasts until the yj-th domino falls. But sometimes, it could be impossible to achieve such plan, so he has to lengthen some dominoes. It costs one dollar to increase the length of a single domino by 1. User ainta wants to know, for each plan, the minimum cost needed to achieve it. Plans are processed independently, i. e. if domino's length is increased in some plan, it doesn't affect its length in other plans. Set of dominos that will fall except xj-th domino and yj-th domino doesn't matter, but the initial push should be on domino xj.

Input

The first line contains an integer n (2 ≤ n ≤ 2 × 105)— the number of dominoes.

Next n lines describe the dominoes. The i-th line (1 ≤ i ≤ n) contains two space-separated integers pi, li (1 ≤ pi, li ≤ 109)— the x-coordinate and the length of the i-th domino. It is guaranteed that p1 < p2 < ... < pn - 1 < pn.

The next line contains an integer q (1 ≤ q ≤ 2 × 105) — the number of plans.

Next q lines describe the plans. The j-th line (1 ≤ j ≤ q) contains two space-separated integers xj, yj (1 ≤ xj < yj ≤ n). It means the j-th plan is, to push the xj-th domino, and shoot a video until the yj-th domino falls.

Output

For each plan, print a line containing the minimum cost needed to achieve it. If no cost is needed, print 0.

Examples

Input

6
1 5
3 3
4 4
9 2
10 1
12 1
4
1 2
2 4
2 5
2 6

Output

0
1
1
2

Note

Consider the example. The dominoes are set like the picture below.

<image>

Let's take a look at the 4th plan. To make the 6th domino fall by pushing the 2nd domino, the length of the 3rd domino (whose x-coordinate is 4) should be increased by 1, and the 5th domino (whose x-coordinate is 9) should be increased by 1 (other option is to increase 4th domino instead of 5th also by 1). Then, the dominoes will fall like in the picture below. Each cross denotes a touch between two dominoes.

<image> <image> <image> <image> <image>

```python
'''
from bisect import bisect,bisect_left

from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *'''

#------------------------------------------------------------------------
import os
import sys

from io import BytesIO, IOBase
# 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")

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

#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------

from types import GeneratorType

def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return wrappedfunc

mod=10**9+7
farr=[1]
ifa=[]

def fact(x,mod=0):
    if mod:
        while x>=len(farr):
            farr.append(farr[-1]*len(farr)%mod)
    else:
        while x>=len(farr):
            farr.append(farr[-1]*len(farr))
    return farr[x]

def ifact(x,mod):
    global ifa
    fact(x,mod)
    ifa.append(pow(farr[-1],mod-2,mod))
    for i in range(x,0,-1):
        ifa.append(ifa[-1]*i%mod)
    ifa.reverse()

def per(i,j,mod=0):
    if i<j: return 0
    if not mod:
        return fact(i)//fact(i-j)
    return farr[i]*ifa[i-j]%mod

def com(i,j,mod=0):
    if i<j: return 0
    if not mod:
        return per(i,j)//fact(j)
    return per(i,j,mod)*ifa[j]%mod

def catalan(n):
    return com(2*n,n)//(n+1)

def isprime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
    if a==0:return b//c*(n+1)
    if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
    m=(a*n+b)//c
    return n*m-floorsum(c,c-b-1,a,m-1)

def inverse(a,m):
    a%=m
    if a<=1: return a
    return ((1-inverse(m,a)*m)//a)%m

def lowbit(n):
    return n&-n

class BIT:
    def __init__(self,arr):
        self.arr=arr
        self.n=len(arr)-1

    def update(self,x,v):
        while x<=self.n:
            self.arr[x]+=v
            x+=x&-x

    def query(self,x):
        ans=0
        while x:
            ans+=self.arr[x]
            x&=x-1
        return ans

class ST:
    def __init__(self,arr):#n!=0
        n=len(arr)
        mx=n.bit_length()#取不到
        self.st=[[0]*mx for i in range(n)]
        for i in range(n):
            self.st[i][0]=arr[i]
        for j in range(1,mx):
            for i in range(n-(1<<j)+1):
                self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
    def query(self,l,r):
        if l>r:return -inf
        s=(r+1-l).bit_length()-1
        return max(self.st[l][s],self.st[r-(1<<s)+1][s])

class DSU:#容量+路径压缩
    def __init__(self,n):
        self.c=[-1]*n

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

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

    def union(self,u,v):
        u,v=self.find(u),self.find(v)
        if u==v:
            return False
        if self.c[u]>self.c[v]:
            u,v=v,u
        self.c[u]+=self.c[v]
        self.c[v]=u
        return True

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

class UFS:#秩+路径
    def __init__(self,n):
        self.parent=[i for i in range(n)]
        self.ranks=[0]*n

    def find(self,x):
        if x!=self.parent[x]:
            self.parent[x]=self.find(self.parent[x])
        return self.parent[x]

    def union(self,u,v):
        pu,pv=self.find(u),self.find(v)
        if pu==pv:
            return False
        if self.ranks[pu]>=self.ranks[pv]:
            self.parent[pv]=pu
            if self.ranks[pv]==self.ranks[pu]:
                self.ranks[pu]+=1
        else:
            self.parent[pu]=pv

def Prime(n):
    c=0
    prime=[]
    flag=[0]*(n+1)
    for i in range(2,n+1):
        if not flag[i]:
            prime.append(i)
            c+=1
        for j in range(c):
            if i*prime[j]>n: break
            flag[i*prime[j]]=prime[j]
            if i%prime[j]==0: break
    return flag

def dij(s,graph):
    d={}
    d[s]=0
    heap=[(0,s)]
    seen=set()
    while heap:
        dis,u=heappop(heap)
        if u in seen:
            continue
        seen.add(u)
        for v,w in graph[u]:
            if v not in d or d[v]>d[u]+w:
                d[v]=d[u]+w
                heappush(heap,(d[v],v))
    return d

def bell(s,g):#bellman-Ford
    dis=AI(n,inf)
    dis[s]=0
    for i in range(n-1):
        for u,v,w in edge:
            if dis[v]>dis[u]+w:
                dis[v]=dis[u]+w
    change=A(n)
    for i in range(n):
        for u,v,w in edge:
            if dis[v]>dis[u]+w:
                dis[v]=dis[u]+w
                change[v]=1
    return dis

def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
    res=[]
    for k in nums:
        i=bisect.bisect_left(res,k)
        if i==len(res):
            res.append(k)
        else:
            res[i]=k
    return len(res)

def RP(nums):#逆序对
    n = len(nums)
    s=set(nums)
    d={}
    for i,k in enumerate(sorted(s),1):
        d[k]=i
    bi=BIT([0]*(len(s)+1))
    ans=0
    for i in range(n-1,-1,-1):
        ans+=bi.query(d[nums[i]]-1)
        bi.update(d[nums[i]],1)
    return ans

class DLN:
    def __init__(self,val):
        self.val=val
        self.pre=None
        self.next=None

def nb(i,j,n,m):
    for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
        if 0<=ni<n and 0<=nj<m:
            yield ni,nj

def topo(n):
    q=deque()
    res=[]
    for i in range(1,n+1):
        if ind[i]==0:
            q.append(i)
            res.append(i)
    while q:
        u=q.popleft()
        for v in g[u]:
            ind[v]-=1
            if ind[v]==0:
                q.append(v)
                res.append(v)
    return res

@bootstrap
def gdfs(r,p):
    for ch in g[r]:
        if ch!=p:
            yield gdfs(ch,r)
    yield None

class SMT:
    def __init__(self,n,query_fn,I):
        self.h = 1
        while 1 << self.h < n:
            self.h += 1
        self.n=1<<self.h
        self.qf=query_fn
        self.tree = [I] * (self.n<<1)
        self.lazy = [0] * self.n

    def build(self, v):
        for k in range(len(v)):
            self.tree[k + self.n] = v[k]
        for k in range(self.n - 1, 0, -1):
            self.tree[k] = self.qf(self.tree[2*k],self.tree[2 * k + 1])

    def apply(self, x, val):
        self.tree[x] = val
        if x < self.n:
            self.lazy[x] = 1

    def pushup(self, x):
        self.tree[x]=self.qf(self.tree[2*x],self.tree[2*x+1])

    def push(self, x):#pushdown
        if self.lazy[x]:
            self.apply(x * 2,0)
            self.apply(x * 2+ 1,0)
            self.lazy[x] = 0

    def set(self,p,x):
        p+=self.n
        for i in range(self.h,0,-1):self.push(p>>i)
        self.tree[p]=x
        for i in range(1,self.h+1):self.pushup(p>>i)

    def get(self,p):
        p+=self.n
        for i in range(self.h,0,-1):self.push(p>>i)
        return self.tree[p]

    def update(self, l, r, h):#左闭右闭
        l += self.n
        r += self.n
        l0=l
        r0=r
        for i in range(self.h,0,-1):
            if (((l>>i)<<i)!=l):self.push(l>>i)
            if ((((r+1)>>i)<<i)!=r+1):self.push(r>>i)
        while l <= r:
            if l & 1:
                self.apply(l, h)
                l += 1
            if not r & 1:
                self.apply(r, h)
                r -= 1
            l>>=1
            r>>=1
        for i in range(1,self.h+1):
            if (((l0>>i)<<i)!=l0):self.pushup(l0>>i)
            if ((((r0+1)>>i)<<i)!=r0+1):
                self.pushup(r0>>i)

    def query(self, l, r):
        l += self.n
        r += self.n
        for i in range(self.h,0,-1):
            if (((l>>i)<<i)!=l):self.push(l>>i)
            if ((((r+1)>>i)<<i)!=r+1):self.push(r>>i)
        ans = 0
        while l <= r:
            if l & 1:
                ans = self.qf(ans, self.tree[l])
                l += 1
            if not r & 1:
                ans = self.qf(ans, self.tree[r])
                r -= 1
            l >>= 1; r >>= 1
        return ans

def add(x,y):
    return x+y
t=1
for i in range(t):
    n=N()
    s=set()
    x=A(n)
    y=A(n)
    for i in range(n):
        p,l=RL()
        x[i]=p
        y[i]=p+l
        s.add(p)
        s.add(y[i])
    s=sorted(s)
    d={x:i for i,x in enumerate(s)}
    k=len(s)-1
    arr=[s[i]-s[i-1] for i in range(1,k+1)]
    smt=SMT(k,add,0)
    smt.build(arr)
    g=G(n)
    q=N()
    ans=A(q)
    for i in range(q):
        a,b=RL()
        a-=1
        b-=1
        g[a].append((i,b))
    for i in range(n-1,-1,-1):
        l=d[x[i]]
        r=d[y[i]]
        smt.update(l,r-1,0)
        for j,cur in g[i]:
            cur=d[x[cur]]
            ans[j]=smt.query(l,cur-1)
    for x in ans:
        print(x)

'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''

```


526_C. Om Nom and Candies

A sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place?

<image>

One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs Wr grams and each blue candy weighs Wb grams. Eating a single red candy gives Om Nom Hr joy units and eating a single blue candy gives Om Nom Hb joy units.

Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than C grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.

Input

The single line contains five integers C, Hr, Hb, Wr, Wb (1 ≤ C, Hr, Hb, Wr, Wb ≤ 109).

Output

Print a single integer — the maximum number of joy units that Om Nom can get.

Examples

Input

10 3 5 2 3

Output

16

Note

In the sample test Om Nom can eat two candies of each type and thus get 16 joy units.

```python
C, Hr, Hb, Wr, Wb = map(int, input().split())
ans = 0
for i in range(10 ** 5):
    if Wr * i <= C:
        ans = max(ans, Hr * i + (C - Wr * i) // Wb * Hb)
for i in range(10 ** 5):
    if Wb * i <= C:
        ans = max(ans, Hb * i + (C - Wb * i) // Wr * Hr)
print(ans)
```


551_D. GukiZ and Binary Operations

We all know that GukiZ often plays with arrays.

Now he is thinking about this problem: how many arrays a, of length n, with non-negative elements strictly less then 2l meet the following condition: <image>? Here operation <image> means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equivalent to &), operation <image> means bitwise OR (in Pascal it is equivalent to <image>, in C/C++/Java/Python it is equivalent to |).

Because the answer can be quite large, calculate it modulo m. This time GukiZ hasn't come up with solution, and needs you to help him!

Input

First and the only line of input contains four integers n, k, l, m (2 ≤ n ≤ 1018, 0 ≤ k ≤ 1018, 0 ≤ l ≤ 64, 1 ≤ m ≤ 109 + 7).

Output

In the single line print the number of arrays satisfying the condition above modulo m.

Examples

Input

2 1 2 10

Output

3

Input

2 1 1 3

Output

1

Input

3 3 2 10

Output

9

Note

In the first sample, satisfying arrays are {1, 1}, {3, 1}, {1, 3}.

In the second sample, only satisfying array is {1, 1}.

In the third sample, satisfying arrays are {0, 3, 3}, {1, 3, 2}, {1, 3, 3}, {2, 3, 1}, {2, 3, 3}, {3, 3, 0}, {3, 3, 1}, {3, 3, 2}, {3, 3, 3}.


5_C. Longest Regular Bracket Sequence

This is yet another problem dealing with regular bracket sequences.

We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.

You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

Input

The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.

Output

Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".

Examples

Input

)((())))(()())

Output

6 2

Input

))(

Output

0 1

```python
string = input()
n = len(string)

stack = []
mapping = [0]*n

# First we create an array where the array called mapping where the index of array
# gives the index of start of opening bracket in string and the value at that index
# gives the index of closing bracket for corresponding opening bracket.

for idx, char in enumerate(string):

	if char == '(':
		# We add idx of ( to stack which will be used as idx in mapping
		stack.append(idx)

	# Map only those ')' which have an opening brace, empty stack signifies
	# closing brace has no opening brace.
	elif char == ')' and stack:
		mapping[stack.pop()] = idx

# Once we have generated the mapping we scan the array the difference between the index and its
# value gives us the len of current regular expression. Now we take the value at that index and
# icrement it to see if there is some non zero value at that location signifing that the regular
# expression can be expanded. We continue this till no more expansion or we have some current length
# more than previous expansions.

i = 0
mx = 0
cnt = 1
tmp_max = 0
prev_join_idx = 0

while i < n:
	# If value present at mapping
	if mapping[i]:
		curr_len = mapping[i] - i + 1

		# if we have some previous regx
		if i == prev_join_idx + 1:
			tmp_max += curr_len
		else:
			tmp_max = curr_len

		# We have found new regx whose len is more than all prev scanned regx
		if tmp_max > mx:
			mx = tmp_max
			cnt = 1
		elif tmp_max == mx:
			cnt += 1

		prev_join_idx = mapping[i]
		i = mapping[i] + 1

	else:
		i +=1

print(mx, cnt)
```


622_A. Infinite Sequence

Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).

Find the number on the n-th position of the sequence.

Input

The only line contains integer n (1 ≤ n ≤ 1014) — the position of the number to find.

Note that the given number is too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

Output

Print the element in the n-th position of the sequence (the elements are numerated from one).

Examples

Input

3

Output

2

Input

5

Output

2

Input

10

Output

4

Input

55

Output

10

Input

56

Output

1

```python
n = int(input())
from math import sqrt
# Find max m such that m(m+1)/2 <= n
m = int((-1 + sqrt(1 + 8*n))/2)
# l is the previous range
l = m * (m + 1) // 2
print(m if n == l else n - l)
```


670_D1. Magic Powder - 1

This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.

Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value ai — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.

Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.

Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.

Input

The first line of the input contains two positive integers n and k (1 ≤ n, k ≤ 1000) — the number of ingredients and the number of grams of the magic powder.

The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie.

The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Output

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

Examples

Input

3 1
2 1 4
11 3 16

Output

4

Input

4 3
4 3 5 6
11 12 14 20

Output

3

Note

In the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.

In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer.

```python
n, k = input().split(" ")
n, k = [int(n), int(k)]
list1 = list(map(int, input().split(" ")))
list2 = list(map(int, input().split(" ")))

low = 0
high = 2*(10**9)
while low < high:
    if high - low % 2 != 0:
        mid = low + (high - low) // 2 + 1
    else:
        mid = low + (high - low)//2
    d = k
    list6 = []
    for i in range(n):
        if list1[i]*mid <= list2[i]:
            continue
        else:
            c = list1[i] * mid - list2[i]
            if d >= c:
                d = d - c
                continue
            else:
                high = mid -1
                break
    if high != mid - 1:
        low = mid

print(low)

```


737_C. Subordinates

There are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior.

There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself.

Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.

Input

The first line contains two positive integers n and s (1 ≤ n ≤ 2·105, 1 ≤ s ≤ n) — the number of workers and the id of the chief.

The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n - 1), where ai is the number of superiors (not only immediate) the worker with id i reported about.

Output

Print the minimum number of workers that could make a mistake.

Examples

Input

3 2
2 0 2

Output

1

Input

5 3
1 0 0 4 1

Output

2

Note

In the first example it is possible that only the first worker made a mistake. Then:

  * the immediate superior of the first worker is the second worker,
  * the immediate superior of the third worker is the first worker,
  * the second worker is the chief.

```python
f = lambda: map(int, input().split())
n, s = f()
c = [0] * n
t = list(f())
for i in t: c[i] += 1
k = t[s - 1]
c[k] -= 1
d = c[0]
c += [d]
d += k > 0
i, j = 1, n
while i < j:
    if c[i]: i += 1
    elif c[j]:
        c[j] -= 1
        i += 1
        d += j < n
    else: j -= 1
print(d)
```