1263_A. Sweet Problem

You have three piles of candies: red, green and blue candies:

  * the first pile contains only red candies and there are r candies in it,
  * the second pile contains only green candies and there are g candies in it,
  * the third pile contains only blue candies and there are b candies in it.

Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.

Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.

Input

The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.

Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.

Output

Print t integers: the i-th printed integer is the answer on the i-th test case in the input.

Example

Input

6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8

Output

1
2
2
10
5
9

Note

In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.

In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.

In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.

```python
from math import ceil
for T in range(int(input())):
    r , g , b = sorted(list(map(int ,input().split())))

    t = b -g
    if t >= r :
        print(r +g)
    else :
        print(r + g - ceil((r-t)/2))

```


1284_D. New Year and Conference

Filled with optimism, Hyunuk will host a conference about how great this new year will be!

The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.

Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).

We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.

A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.

A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.

Input

The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.

Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).

Output

Print "YES" if Hyunuk will be happy. Print "NO" otherwise.

You can print each letter in any case (upper or lower).

Examples

Input

2
1 2 3 6
3 4 7 8

Output

YES

Input

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

Output

NO

Input

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

Output

YES

Note

In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.

In first and third example, venue-sensitive set does not exist.

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

n=int(input())

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

CA=[]
CB=[]

for ind,(a,b,c,d) in enumerate(C):
    CA.append((a,0,ind))
    CA.append((b,1,ind))

    CB.append((c,0,ind))
    CB.append((d,1,ind))

CA.sort()
CB.sort()

SMAX=[]
EMIN=[]
FINISHED=[0]*n

for time,flag,ind in CA:

    if flag==0:
        heapq.heappush(SMAX,(-C[ind][2],ind))
        heapq.heappush(EMIN,(C[ind][3],ind))

        while FINISHED[SMAX[0][1]]:
            heapq.heappop(SMAX)

        while FINISHED[EMIN[0][1]]:
            heapq.heappop(EMIN)

        if -SMAX[0][0]>EMIN[0][0]:
            print("NO")
            sys.exit()

    else:
        FINISHED[ind]=1

SMAX=[]
EMIN=[]
FINISHED=[0]*n

for time,flag,ind in CB:

    if flag==0:
        heapq.heappush(SMAX,(-C[ind][0],ind))
        heapq.heappush(EMIN,(C[ind][1],ind))

        while FINISHED[SMAX[0][1]]:
            heapq.heappop(SMAX)

        while FINISHED[EMIN[0][1]]:
            heapq.heappop(EMIN)

        if -SMAX[0][0]>EMIN[0][0]:
            print("NO")
            sys.exit()

    else:
        FINISHED[ind]=1

print("YES")

```


138_B. Digits Permutations

Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.

Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.

Given number n, can you find the two digit permutations that have this property?

Input

The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.

Output

Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.

Examples

Input

198

Output

981
819

Input

500

Output

500
500

```python
import itertools

def countZeroes(s):
    ret = 0
    for i in s:
        if i != '0':
            break
        ret += 1
    return ret

def stupid(n):
    ansMax = 0
    bn1 = n
    bn2 = n
    for n1 in itertools.permutations(n):
        for n2 in itertools.permutations(n):
            val = str(int(''.join(n1)) + int(''.join(n2)))[::-1]
            cnt = countZeroes(val)
            if cnt > ansMax:
                ansMax = cnt
                bn1 = ''.join(n1)
                bn2 = ''.join(n2)
    return (bn1, bn2)

def solution(n):
    ansMax = n.count('0')
    bestN1 = n.replace('0', '') + ansMax * '0'
    bestN2 = n.replace('0', '') + ansMax * '0'

    for i in range(1, 10):
        cnt1 = [n.count(str(j)) for j in range(10)]
        cnt2 = [n.count(str(j)) for j in range(10)]

        if cnt1[i] == 0 or cnt2[10 - i] == 0:
            continue
        cnt1[i] -= 1
        cnt2[10 - i] -= 1
        curN1 = str(i)
        curN2 = str(10 - i)
        ansCur = 1
        for j in range(10):
            addend = min(cnt1[j], cnt2[9 - j])
            ansCur += addend

            cnt1[j] -= addend
            cnt2[9 - j] -= addend

            curN1 += str(j) * addend
            curN2 += str(9 - j) * addend

        if cnt1[0] > 0 and cnt2[0] > 0:
            addend = min(cnt1[0], cnt2[0])
            ansCur += addend

            cnt1[0] -= addend
            cnt2[0] -= addend

            curN1 = '0' * addend + curN1
            curN2 = '0' * addend + curN2

        if ansCur > ansMax:
            ansMax = ansCur
            f = lambda x: str(x[0]) * x[1]
            bestN1 = ''.join(map(f, enumerate(cnt1))) + curN1[::-1]
            bestN2 = ''.join(map(f, enumerate(cnt2))) + curN2[::-1]

    return (bestN1, bestN2)

n = input()
print('\n'.join(solution(n)))

```


1454_F. Array Partition

You are given an array a consisting of n integers.

Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.

Your task is to choose three positive (greater than 0) integers x, y and z such that:

  * x + y + z = n;
  * max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).

In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).

Among all such triples (partitions), you can choose any.

You have to answer t independent test cases.

Input

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

The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.

The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.

It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).

Output

For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.

If there are several answers, you can print any.

Example

Input

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

Output

YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4

```python
# Author : nitish420 --------------------------------------------------------------------
import math
import os
import sys
from io import BytesIO, IOBase
# mod=10**9+7
from collections import defaultdict
from bisect import bisect_left

def main():
	for _ in range(int(input())):
		n=int(input())
		arr=list(map(int,input().split()))
		dct=defaultdict(list)
		for i,item in enumerate(arr):
			dct[item].append(i)

		col=n.bit_length()
		sparse=[[-1 for _ in range(col)] for _ in range(n)]
		for c in range(col):
			for r in range(n):
				if c==0:
					sparse[r][c]=r
					continue
				if r+(1<<c)<=n:
					z=1<<c
					if arr[sparse[r][c-1]]<arr[sparse[r+(z>>1)][c-1]]:
						sparse[r][c]=sparse[r][c-1]
					else:
						sparse[r][c]=sparse[r+(z>>1)][c-1]
				else:
					break
		postmax=[0]*(n+1)
		dctz=dict()
		for i in range(n):
			postmax[n-i-1]=max(postmax[n-i],arr[n-i-1])

		postmax.pop()
		for i in range(n-2,-1,-1):
			if postmax[i]!=postmax[i+1]:
				dctz[postmax[i+1]]=i
		dctz[postmax[0]]=-1

		# print(postmax)
		def findmin(l,r):
			z=r-l+1
			k=z.bit_length()-1
			ans=arr[sparse[l][k]]
			z-=(1<<k)
			if z:
				ans=min(ans,arr[sparse[l+z][k]])
			return ans

		pre=0
		ans=0
		for i in range(n):
			pre=max(pre,arr[i])
			if pre in dctz:
				y=dct[pre]
				x=bisect_left(y,i+1)
				if x!=len(y):
					z=max(y[x],dctz[pre])
					if z!=n-1 and findmin(i+1,z)==pre and postmax[z+1]==pre:
						ans=[i+1,z-i,n-z-1]
						break
		if ans:
			print("YES")
			print(*ans)
		else:
			print("NO")

# 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')

# endregion

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


1479_A. Searching Local Minimum

This is an interactive problem.

Homer likes arrays a lot and he wants to play a game with you.

Homer has hidden from you a permutation a_1, a_2, ..., a_n of integers 1 to n. You are asked to find any index k (1 ≤ k ≤ n) which is a local minimum.

For an array a_1, a_2, ..., a_n, an index i (1 ≤ i ≤ n) is said to be a local minimum if a_i < min\\{a_{i-1},a_{i+1}\}, where a_0 = a_{n+1} = +∞. An array is said to be a permutation of integers 1 to n, if it contains all integers from 1 to n exactly once.

Initially, you are only given the value of n without any other information about this permutation.

At each interactive step, you are allowed to choose any i (1 ≤ i ≤ n) and make a query with it. As a response, you will be given the value of a_i.

You are asked to find any index k which is a local minimum after at most 100 queries.

Interaction

You begin the interaction by reading an integer n (1≤ n ≤ 10^5) on a separate line.

To make a query on index i (1 ≤ i ≤ n), you should output "? i" in a separate line. Then read the value of a_i in a separate line. The number of the "?" queries is limited within 100.

When you find an index k (1 ≤ k ≤ n) which is a local minimum, output "! k" in a separate line and terminate your program.

In case your query format is invalid, or you have made more than 100 "?" queries, you will receive Wrong Answer verdict.

After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:

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

Hack Format

The first line of the hack should contain a single integer n (1 ≤ n ≤ 10^5).

The second line should contain n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n).

Example

Input

5
3
2
1
4
5

Output

? 1
? 2
? 3
? 4
? 5
! 3

Note

In the example, the first line contains an integer 5 indicating that the length of the array is n = 5.

The example makes five "?" queries, after which we conclude that the array is a = [3,2,1,4,5] and k = 3 is local minimum.

```python
from collections import deque
from typing import List
from sys import stdout

class ContestParser:
    """Helper module to read/write

    Commonly in programming competition input for a problem is given with space separated numbers and strings.
    Standard python input() functionality is clunky when dealing with such input. This parser can tokenize inputs and convert them to proper types.
    """

    def __init__(self):
        self.buffer = deque()

    def next_token(self) -> str:
        if len(self.buffer) == 0:
            self.buffer.extend(input().split())
        return self.buffer.popleft()

    def next_int(self) -> int:
        return int(self.next_token())

parser = ContestParser()

def ask(v: int) -> int:
    print("? {}".format(v))
    stdout.flush()
    return parser.next_int()

def answer(v: int) -> int:
    print("! {}".format(v))

if __name__ == '__main__':
    n = parser.next_int()
    left = 1
    right = n
    while left < right:
        mid = (left + right) // 2
        b_1 = ask(mid)
        b_2 = ask(mid + 1)
        if b_1 < b_2:
            right = mid
        else:
            left = mid + 1
    answer(left)

```


1505_G. Encoded message

Input

The first line of the input contains a single integer N (1 ≤ N ≤ 24). The next N lines contain 5 space-separated integers each. The first three integers will be between 0 and 2, inclusive. The last two integers will be between 0 and 3, inclusive. The sum of the first three integers will be equal to the sum of the last two integers.

Output

Output the result – a string of lowercase English letters.

Examples

Input

1
1 0 0 1 0

Output

a

Input

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

Output

codeforcez


1529_A. Eshag Loves Big Arrays

Eshag has an array a consisting of n integers.

Eshag can perform the following operation any number of times: choose some subsequence of a and delete every element from it which is strictly larger than AVG, where AVG is the average of the numbers in the chosen subsequence.

For example, if a = [1 , 4 , 3 , 2 , 4] and Eshag applies the operation to the subsequence containing a_1, a_2, a_4 and a_5, then he will delete those of these 4 elements which are larger than (a_1+a_2+a_4+a_5)/(4) = 11/4, so after the operation, the array a will become a = [1 , 3 , 2].

Your task is to find the maximum number of elements Eshag can delete from the array a by applying the operation described above some number (maybe, zero) times.

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

Input

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

The first line of each test case contains an integer n (1≤ n≤ 100) — the length of the array a.

The second line of each test case contains n integers a_1, a_2, …, a_n (1≤ a_i ≤ 100) — the elements of the array a.

Output

For each test case print a single integer — the maximum number of elements Eshag can delete from the array a.

Example

Input

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

Output

3
0
3

Note

Consider the first test case.

Initially a = [1, 1, 1, 2, 2, 3].

In the first operation, Eshag can choose the subsequence containing a_1, a_5 and a_6, their average is equal to (a_1 + a_5 + a_6)/(3) = 6/3 = 2. So a_6 will be deleted.

After this a = [1, 1, 1, 2, 2].

In the second operation, Eshag can choose the subsequence containing the whole array a, the average of all its elements is equal to 7/5. So a_4 and a_5 will be deleted.

After this a = [1, 1, 1].

In the second test case, Eshag can't delete any element.

```python
import sys
#import random
from bisect import bisect_right as rb
from collections import deque
#sys.setrecursionlimit(10**8)
from queue import PriorityQueue
#from math import *
input_ = lambda: sys.stdin.readline().strip("\r\n")
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab,bc,cd : ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x : print(x)
prinT = lambda x : print(x)
f = lambda : sys.stdout.flush()
inv =lambda x:pow(x,mod-2,mod)
mod = 10**9 + 7

for _ in range (ii()) :
    n = ii()
    a = il()

    t = 0
    x = min(a)

    for i in a :
        if (i == x) :
            t += 1

    print(n-t)

```


160_A. Twins

Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.

Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.

As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

Input

The first line contains integer n (1 ≤ n ≤ 100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the coins' values. All numbers are separated with spaces.

Output

In the single line print the single number — the minimum needed number of coins.

Examples

Input

2
3 3

Output

2

Input

3
2 1 2

Output

2

Note

In the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.

In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.

```python
n = int(input())
a = sorted(list(map(int, input().split())))[::-1]
b = sum(a)//2
sum1 = count = 0
for i in a:
	sum1+=i
	count+=1
	if sum1>b:
		break
print(count)
```


227_C. Flying Saucer Segments

An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).

The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one — to the 1-st and the 3-rd ones, the 3-rd one — only to the 2-nd one. The transitions are possible only between the adjacent sections.

The spacecraft team consists of n aliens. Each of them is given a rank — an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.

Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B.

At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.

Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m.

Input

The first line contains two space-separated integers: n and m (1 ≤ n, m ≤ 109) — the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly.

Output

Print a single number — the answer to the problem modulo m.

Examples

Input

1 10

Output

2

Input

3 8

Output

2

Note

In the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes.

To briefly describe the movements in the second sample we will use value <image>, which would correspond to an alien with rank i moving from the segment in which it is at the moment, to the segment number j. Using these values, we will describe the movements between the segments in the second sample: <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>, <image>; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2.

```python
def binpow(a,n):
    res = 1
    while(n>0):
        if(n&1):
            res = (res*a)%m
        a = (a*a)%m
        n>>=1
    return res

n,m = map(int,input().split())
ans = binpow(3,n)-1
if(ans%m ==0 and ans != 0):
    print(m-1)
else:
    print(ans%m)
```


251_A. Points on Line

Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.

Note that the order of the points inside the group of three chosen points doesn't matter.

Input

The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.

It is guaranteed that the coordinates of the points in the input strictly increase.

Output

Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.

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

Examples

Input

4 3
1 2 3 4

Output

4

Input

4 2
-3 -2 -1 0

Output

2

Input

5 19
1 10 20 30 50

Output

1

Note

In the first sample any group of three points meets our conditions.

In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.

In the third sample only one group does: {1, 10, 20}.

```python
from sys import stdin
a,b=map(int,stdin.readline().split());a+=1
z=[1]+list(map(int,stdin.readline().split()));i,j=1,1;ans=0
r=lambda x:(x*(x+1))//2
while i<a:
    if j<=i:j=i
    while j<a and abs(z[j]-z[i])<=b:j+=1
    if j-i-1>=2:ans+=r(j-i-2)
    i+=1
print(ans)
```


276_B. Little Girl and Game

The Little Girl loves problems on games very much. Here's one of them.

Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:

  * The players move in turns; In one move the player can remove an arbitrary letter from string s.
  * If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't.

Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.

Input

The input contains a single line, containing string s (1 ≤ |s| ≤ 103). String s consists of lowercase English letters.

Output

In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.

Examples

Input

aba

Output

First

Input

abca

Output

Second

```python
import sys

#sys.stdin = open('in', 'r')
#sys.stdout = open('out', 'w')

def Out(x):
    sys.stdout.write(str(x) + '\n')

def In():
    return sys.stdin.readline().strip()

def main():
    s = str(input())
    Map = {}

    for word in s:
        if word not in Map:
            Map[word] = 1
        else:
            Map[word] += 1

    odd = 0
    for key, value in Map.items():
        if value&1 == 1:
            odd +=1

    if odd&1 or odd == 0:
        print("First")
    else:
        print("Second")

if __name__ == '__main__':
    main()

```


322_B. Ciel and Flowers

Fox Ciel has some flowers: r red flowers, g green flowers and b blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:

  * To make a "red bouquet", it needs 3 red flowers.
  * To make a "green bouquet", it needs 3 green flowers.
  * To make a "blue bouquet", it needs 3 blue flowers.
  * To make a "mixing bouquet", it needs 1 red, 1 green and 1 blue flower.

Help Fox Ciel to find the maximal number of bouquets she can make.

Input

The first line contains three integers r, g and b (0 ≤ r, g, b ≤ 109) — the number of red, green and blue flowers.

Output

Print the maximal number of bouquets Fox Ciel can make.

Examples

Input

3 6 9

Output

6

Input

4 4 4

Output

4

Input

0 0 0

Output

0

Note

In test case 1, we can make 1 red bouquet, 2 green bouquets and 3 blue bouquets.

In test case 2, we can make 1 red, 1 green, 1 blue and 1 mixing bouquet.

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

max_mix = min(a,b,c)

res = -99999999999999
for i in range (0,min(3,max_mix)+1):
      pos = (i+(a-i)//3 + (b-i)//3 + (c-i)//3)
      res=max(res,pos)

print(res)
```


370_A. Rook, Bishop and King

Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 × 8 table. A field is represented by a pair of integers (r, c) — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules:

  * A rook moves any number of fields horizontally or vertically.
  * A bishop moves any number of fields diagonally.
  * A king moves one field in any direction — horizontally, vertically or diagonally.

<image> The pieces move like that

Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (r1, c1) to field (r2, c2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.

Input

The input contains four integers r1, c1, r2, c2 (1 ≤ r1, c1, r2, c2 ≤ 8) — the coordinates of the starting and the final field. The starting field doesn't coincide with the final one.

You can assume that the chessboard rows are numbered from top to bottom 1 through 8, and the columns are numbered from left to right 1 through 8.

Output

Print three space-separated integers: the minimum number of moves the rook, the bishop and the king (in this order) is needed to move from field (r1, c1) to field (r2, c2). If a piece cannot make such a move, print a 0 instead of the corresponding number.

Examples

Input

4 3 1 6

Output

2 1 3

Input

5 5 5 6

Output

1 0 1

```python
def benteng(x1,y1,x2,y2):
    if(x1==x2 or y1==y2):
        return 1
    else:
        return 2

def mentri(x1,y1,x2,y2):
    if(abs(x1-x2)==abs(y1-y2)):
        return 1
    if((abs(x1-x2)+abs(y1-y2))%2==0):
        return 2
    return 0

def raja(x1,y1,x2,y2):
    a=abs(x1-x2)
    b=abs(y1-y2)
    if(a>b):
        return a
    else:
        return b

tp=str(input()).split()

print(benteng(int(tp[0]),int(tp[1]),int(tp[2]),int(tp[3])),mentri(int(tp[0]),int(tp[1]),int(tp[2]),int(tp[3])),raja(int(tp[0]),int(tp[1]),int(tp[2]),int(tp[3])))

```


391_F1. Stock Trading

This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points.

Manao has developed a model to predict the stock price of a company over the next n days and wants to design a profit-maximizing trading algorithm to make use of these predictions. Unfortunately, Manao's trading account has the following restrictions:

  * It only allows owning either zero or one shares of stock at a time;
  * It only allows buying or selling a share of this stock once per day;
  * It allows a maximum of k buy orders over the next n days;

For the purposes of this problem, we define a trade to a be the act of buying one share of stock on day i, then holding the stock until some day j > i at which point the share is sold. To restate the above constraints, Manao is permitted to make at most k non-overlapping trades during the course of an n-day trading period for which Manao's model has predictions about the stock price.

Even though these restrictions limit the amount of profit Manao can make compared to what would be achievable with an unlimited number of trades or the ability to hold more than one share at a time, Manao still has the potential to make a lot of money because Manao's model perfectly predicts the daily price of the stock. For example, using this model, Manao could wait until the price is low, then buy one share and hold until the price reaches a high value, then sell for a profit, and repeat this process up to k times until n days have passed.

Nevertheless, Manao is not satisfied by having a merely good trading algorithm, and wants to develop an optimal strategy for trading subject to these constraints. Help Manao achieve this goal by writing a program that will determine when to buy and sell stock to achieve the greatest possible profit during the n-day trading period subject to the above constraints.

Input

The first line contains two integers n and k, separated by a single space, with <image>. The i-th of the following n lines contains a single integer pi (0 ≤ pi ≤ 1012), where pi represents the price at which someone can either buy or sell one share of stock on day i.

The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.

  * In subproblem F1 (8 points), n will be between 1 and 3000, inclusive.
  * In subproblem F2 (15 points), n will be between 1 and 100000, inclusive.
  * In subproblem F3 (10 points), n will be between 1 and 4000000, inclusive.

Output

For this problem, the program will only report the amount of the optimal profit, rather than a list of trades that can achieve this profit.

Therefore, the program should print one line containing a single integer, the maximum profit Manao can achieve over the next n days with the constraints of starting with no shares on the first day of trading, always owning either zero or one shares of stock, and buying at most k shares over the course of the n-day trading period.

Examples

Input

10 2
2
7
3
9
8
7
9
7
1
9

Output

15

Input

10 5
2
7
3
9
8
7
9
7
1
9

Output

21

Note

In the first example, the best trade overall is to buy at a price of 1 on day 9 and sell at a price of 9 on day 10 and the second best trade overall is to buy at a price of 2 on day 1 and sell at a price of 9 on day 4. Since these two trades do not overlap, both can be made and the profit is the sum of the profits of the two trades. Thus the trade strategy looks like this:

    2    | 7    | 3    | 9    | 8    | 7    | 9    | 7    | 1    | 9
    buy  |      |      | sell |      |      |      |      | buy  | sell

The total profit is then (9 - 2) + (9 - 1) = 15.

In the second example, even though Manao is allowed up to 5 trades there are only 4 profitable trades available. Making a fifth trade would cost Manao money so he only makes the following 4:

    2    | 7    | 3    | 9    | 8    | 7    | 9    | 7    | 1    | 9
    buy  | sell | buy  | sell |      | buy  | sell |      | buy  | sell

The total profit is then (7 - 2) + (9 - 3) + (9 - 7) + (9 - 1) = 21.

```python
import sys

ammount_prices, days_for_trading=map(int, input().split())
stonks=[]
for i in range (0, ammount_prices):
    price=int(sys.stdin.readline())
    stonks.append(price)

def get_max(days_for_trading, stonks):
    size_prices = len(stonks)
    if size_prices == 0 or size_prices == 1 or days_for_trading == 0:
        return 0
    if days_for_trading >= size_prices/2:
        profit = 0
        for i in range(size_prices-1):
            diff = stonks[i + 1] - stonks[i]
            if diff > 0:
                profit += diff
        return profit

    hold = days_for_trading * [float('-inf')]
    hold_prev = days_for_trading * [float('-inf')]
    release = days_for_trading * [float('-inf')]
    release_prev = days_for_trading * [float('-inf')]

    for price in stonks:
        for j in range(0, days_for_trading):
            if j == 0:
                hold[j] = max(-price, hold_prev[j])
            else:
                hold[j] = max(release_prev[j - 1] - price, hold_prev[j])
            release[j] = max(hold_prev[j] + price, release_prev[j])
        hold_prev = hold
        release_prev = release
    return release[-1]

print(get_max(days_for_trading, stonks))
```


441_B. Valera and Fruits

Valera loves his garden, where n fruit trees grow.

This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).

Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?

Input

The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day.

Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.

Output

Print a single integer — the maximum number of fruit that Valera can collect.

Examples

Input

2 3
1 5
2 3

Output

8

Input

5 10
3 20
2 20
1 20
4 20
5 20

Output

60

Note

In the first sample, in order to obtain the optimal answer, you should act as follows.

  * On the first day collect 3 fruits from the 1-st tree.
  * On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree.
  * On the third day collect the remaining fruits from the 2-nd tree.

In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.

```python
frukti_po_dnyam = {}
n, resurs =map(int,input().split(' '))

for i in range(n):
    den, chislo_fruktov = map(int, input().split(' '))
    if den in frukti_po_dnyam:
        frukti_po_dnyam[den] += chislo_fruktov
    else:
        frukti_po_dnyam[den] = chislo_fruktov
    if den + 1 not in frukti_po_dnyam:
         frukti_po_dnyam[den + 1] = 0

def ubir(chislo, vichet):
    tmp = chislo-vichet
    if tmp<0:
        return 0, -tmp
    return tmp, 0

vsego = 0

# frukti_po_dnyam[max(frukti_po_dnyam.keys())+1] =0
for i in sorted(frukti_po_dnyam):
    ostatok = resurs
    if i-1 in frukti_po_dnyam:
        frukti_po_dnyam[i-1], ostatok =  ubir(frukti_po_dnyam[i-1], ostatok)
    frukti_po_dnyam[i], ostatok  = ubir(frukti_po_dnyam[i], ostatok)
    vsego+= resurs - ostatok

print (vsego)
```


463_C. Gargari and Bishops

Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.

He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number x written on it, if this cell is attacked by one of the bishops Gargari will get x dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.

We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).

Input

The first line contains a single integer n (2 ≤ n ≤ 2000). Each of the next n lines contains n integers aij (0 ≤ aij ≤ 109) — description of the chessboard.

Output

On the first line print the maximal number of dollars Gargari will get. On the next line print four integers: x1, y1, x2, y2 (1 ≤ x1, y1, x2, y2 ≤ n), where xi is the number of the row where the i-th bishop should be placed, yi is the number of the column where the i-th bishop should be placed. Consider rows are numbered from 1 to n from top to bottom, and columns are numbered from 1 to n from left to right.

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

Examples

Input

4
1 1 1 1
2 1 1 0
1 1 1 0
1 0 0 1

Output

12
2 2 3 2

```python
import sys
input=sys.stdin.buffer.readline
t=1
for __ in range(t):
    a=[]
    n=int(input())
    for i in range(n):
        b=list(map(int,input().split()))
        a.append(b)
    dr={}
    di={}
    for i in range(n):
        for j in range(n):
            dr[i+j]=dr.get(i+j,0)+a[i][j]
            di[i+n-j+1]=di.get(i+n-j+1,0)+a[i][j]
    ind1=[0]*2
    ind2=[0]*2
    maxi1=0
    maxi2=0
    for i in range(n):
        for j in range(n):
            #if maxi<(dr[i+j]+di[i+n-j+1]-a[i][j]):
            if ((i+j)&1)==1:
                if maxi1<=(dr[i+j]+di[i+n-j+1]-a[i][j]):
                    maxi1=(dr[i+j]+di[i+n-j+1]-a[i][j])
                    ind1[0]=i+1
                    ind1[1]=j+1
            else:
                if maxi2<=(dr[i+j]+di[i+n-j+1]-a[i][j]):
                    maxi2=(dr[i+j]+di[i+n-j+1]-a[i][j])
                    ind2[0]=i+1
                    ind2[1]=j+1

    print(maxi1+maxi2)
    print(ind1[0],ind1[1],ind2[0],ind2[1])
```


487_B. Strip

Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.

Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:

  * Each piece should contain at least l numbers.
  * The difference between the maximal and the minimal number on the piece should be at most s.

Please help Alexandra to find the minimal number of pieces meeting the condition above.

Input

The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 105, 0 ≤ s ≤ 109, 1 ≤ l ≤ 105).

The second line contains n integers ai separated by spaces ( - 109 ≤ ai ≤ 109).

Output

Output the minimal number of strip pieces.

If there are no ways to split the strip, output -1.

Examples

Input

7 2 2
1 3 1 2 4 1 2

Output

3

Input

7 2 2
1 100 1 100 1 100 1

Output

-1

Note

For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].

For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists.

```python
def split(a,n,s,l):
    pieces = []

    i = 1
    tmpmin = a[0]
    tmpmax = a[0]
    tmppc  = [a[0]]
    while i<n:
        if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s:
            tmppc.append(a[i])
            if a[i]<tmpmin: tmpmin=a[i]
            elif a[i]>tmpmax: tmpmax = a[i]
        else:
            pieces.append(tmppc)
            tmppc = [a[i]]
            tmpmin = a[i]
            tmpmax = a[i]
        i += 1
    pieces.append(tmppc)

    fail = False
    for j in range(len(pieces)):
        if len(pieces[j])<l:
            if j>0:
                prevpc = pieces[j-1]
                minj = min(pieces[j])
                maxj = max(pieces[j])

                while len(pieces[j])<l:
                    tmp = prevpc.pop()
                    if abs(tmp-minj)<=s and abs(tmp-maxj)<=s:
                        pieces[j].insert(0,tmp)
                        if tmp<minj: minj=tmp
                        elif tmp>maxj: maxj=tmp
                    else:
                        return -1
                    if len(prevpc)<l:
                        return -1
            else:
                return -1
    return len(pieces)

n,s,l = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]

res = split(a,n,s,l)
if res<0:
    a.reverse()
    res = split(a,n,s,l)
print(res)

```


510_A. Fox And Snake

Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.

A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.

Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').

Consider sample tests in order to understand the snake pattern.

Input

The only line contains two integers: n and m (3 ≤ n, m ≤ 50).

n is an odd number.

Output

Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.

Examples

Input

3 3

Output

###
..#
###

Input

3 4

Output

####
...#
####

Input

5 3

Output

###
..#
###
#..
###

Input

9 9

Output

#########
........#
#########
#........
#########
........#
#########
#........
#########

```python
n,m=map(int,input().split())
s="."*(m-1)+"#"
#print(s)
for i in range(n):
    if i%2==0:print("#"*m)
    else:
        print(s)
        s=s[::-1]
```


535_B. Tavas and SaDDas

Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."

<image>

The problem is:

You are given a lucky number n. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

If we sort all lucky numbers in increasing order, what's the 1-based index of n?

Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.

Input

The first and only line of input contains a lucky number n (1 ≤ n ≤ 109).

Output

Print the index of n among all lucky numbers.

Examples

Input

4

Output

1

Input

7

Output

2

Input

77

Output

6

```python
a = input().replace("4",'0').replace("7",'1')
sumA = 0
for x in range(len(a)) : sumA += 2**x
print((int(a,2)+sumA))

```


55_C. Pie or die

Volodya and Vlad play the following game. There are k pies at the cells of n × m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.

<image>

Input

First line contains 3 integers, separated by space: 1 ≤ n, m ≤ 100 — dimensions of the board and 0 ≤ k ≤ 100 — the number of pies. Each of the next k lines contains 2 integers, separated by space: 1 ≤ x ≤ n, 1 ≤ y ≤ m — coordinates of the corresponding pie. There could be more than one pie at a cell.

Output

Output only one word: "YES" — if Volodya wins, "NO" — otherwise.

Examples

Input

2 2 1
1 2

Output

YES

Input

3 4 0

Output

NO

Input

100 50 2
50 25
50 25

Output

NO

```python
n, m, k = [int(x) for x in input().split()]
canwin = False
for i in range(k):
  x, y = [int(x) for x in input().split()]
  canwin |= x < 6 or n - x < 5
  canwin |= y < 6 or m - y < 5
print("YES" if canwin else "NO")

```


608_A. Saitama Destroys Hotel

Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.

The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.

Input

The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively.

The next n lines each contain two space-separated integers fi and ti (1 ≤ fi ≤ s, 1 ≤ ti ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.

Output

Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.

Examples

Input

3 7
2 1
3 8
5 2

Output

11

Input

5 10
2 77
3 33
8 21
9 12
10 64

Output

79

Note

In the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:

1. Move to floor 5: takes 2 seconds.

2. Pick up passenger 3.

3. Move to floor 3: takes 2 seconds.

4. Wait for passenger 2 to arrive: takes 4 seconds.

5. Pick up passenger 2.

6. Go to floor 2: takes 1 second.

7. Pick up passenger 1.

8. Go to floor 0: takes 2 seconds.

This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.

```python
I=lambda:map(int,input().split())
n,s=I()
print(max(max(sum(I()),s)for _ in '0'*n))
```


792_F. Mages and Monsters

Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.

Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal x·z damage and spend y·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.

Also Vova can fight monsters. Every monster is characterized by two values tj and hj — monster kills Vova's character in tj seconds and has hj health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.

Vova's character kills a monster, if he deals hj damage to it in no more than tj seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in tj seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.

You have to write a program which can answer two types of queries:

  * 1 x y — Vova's character learns new spell which deals x damage per second and costs y mana per second.
  * 2 t h — Vova fights the monster which kills his character in t seconds and has h health points.

Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.

For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.

Input

The first line contains two integer numbers q and m (2 ≤ q ≤ 105, 1 ≤ m ≤ 1012) — the number of queries and the amount of mana at the beginning of every fight.

i-th of each next q lines contains three numbers ki, ai and bi (1 ≤ ki ≤ 2, 1 ≤ ai, bi ≤ 106).

Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (j = 0 if there were none of these).

  * If ki = 1, then character learns spell with x = (ai + j) mod 106 + 1, y = (bi + j) mod 106 + 1.
  * If ki = 2, then you have to determine if Vova is able to win the fight against monster with t = (ai + j) mod 106 + 1, h = (bi + j) mod 106 + 1.

Output

For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.

Example

Input

3 100
1 4 9
2 19 49
2 19 49

Output

YES
NO

Note

In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana.

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

# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)

[q, m] = map(int, input().strip().split())
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]

mod = 10**6

j = 0
spell_chull = [(0, 0)]  # lower hull _/

def is_right(xy0, xy1, xy):
	(x0, y0) = xy0
	(x1, y1) = xy1
	(x, y) = xy
	return (x0 - x) * (y1 - y) >= (x1 - x) * (y0 - y)

def in_chull(x, y):
	i = 0
	if x > spell_chull[-1][0]:
		return False
	while spell_chull[i][0] < x:
		i += 1
	if spell_chull[i][0] == x:
		return spell_chull[i][1] <= y
	else:
		return is_right(spell_chull[i - 1], spell_chull[i], (x, y))

def add_spell(x, y):
	global spell_chull
	if in_chull(x, y):
		return
	i_left = 0
	while i_left < len(spell_chull) - 1 and not is_right(spell_chull[i_left + 1], spell_chull[i_left], (x, y)):
		i_left += 1
	i_right = i_left + 1
	while i_right < len(spell_chull) - 1 and is_right(spell_chull[i_right + 1], spell_chull[i_right], (x, y)):
		i_right += 1
	if i_right == len(spell_chull) - 1 and x >= spell_chull[-1][0]:
		i_right += 1
	spell_chull = spell_chull[:i_left + 1] + [(x, y)] + spell_chull[i_right:]

for i, qi in enumerate(qis):
	(k, a, b) = qi
	x = (a + j) % mod + 1
	y = (b + j) % mod + 1
	if k == 1:
		add_spell(x, y)
	else:  #2
		if in_chull(y / x, m / x):
			print ('YES')
			j = i + 1
		else:
			print ('NO')

```


813_C. The Tag Game

Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.

Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.

The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.

You should write a program which will determine how many moves will the game last.

Input

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

Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.

Output

Print the total number of moves Alice and Bob will make.

Examples

Input

4 3
1 2
2 3
2 4

Output

4

Input

5 2
1 2
2 3
3 4
2 5

Output

6

Note

In the first example the tree looks like this:

<image>

The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:

B: stay at vertex 3

A: go to vertex 2

B: stay at vertex 3

A: go to vertex 3

In the second example the tree looks like this:

<image>

The moves in the optimal strategy are:

B: go to vertex 3

A: go to vertex 2

B: go to vertex 4

A: go to vertex 3

B: stay at vertex 4

A: go to vertex 4

```python
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict,deque
n,x=list(map(int,input().split()))
edge=defaultdict(list)
child=defaultdict(list)
for i in range(n-1):
    u,v=list(map(int,input().split()))
    edge[u].append(v)
    edge[v].append(u)
def bfsDistance(node):
    dist=[-1]*(n+1)
    vis[node]=1
    q=deque([node])
    dist[node]=0
    temp=0
    while q:
        cur=q.popleft()
        traverse.append(cur)
        for j in edge[cur]:
            if vis[j]==0:
                q.append(j)
                vis[j]=1
                dist[j]=dist[cur]+1
    return dist
def dfsFindLeaf(node):
    vis[node]=1
    stack=[node]
    while stack:
        cur=stack.pop()
        a=0
        for j in edge[cur]:
            if vis[j]==0:
                stack.append(j)
                if node==1:
                    child[cur].append(j)
                vis[j]=1
                a+=1
        if a==0:
            depth[cur]=0
vis=[0]*(n+1)
depth=[-1]*(n+1)
dfsFindLeaf(1)
vis=[0]*(n+1)
traverse=[]
arr1=bfsDistance(1)
vis=[0]*(n+1)
arr2=bfsDistance(x)
lis=[]
l=0
for i in range(1,n+1):
    if i!=1 and i!=x and arr1[i]+arr2[i]==arr1[x]:
        lis.append(i)
        l+=1
traverse.reverse()
for i in range(n):
    if depth[traverse[i]]==-1:
        maxi=0
        for j in child[traverse[i]]:
            maxi=max(depth[j]+1,maxi)
        depth[traverse[i]]=maxi
ans=2*(arr1[x]+depth[x])
for i in range(l):
    if arr1[lis[i]]>arr2[lis[i]]:
        temp=2*(arr1[lis[i]]+depth[lis[i]])
        ans=max(ans,temp)
print(ans)

```


839_B. Game of the Rows

Daenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains ai soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two seats neighbor, if they are in the same row and in seats {1, 2}, {3, 4}, {4, 5}, {5, 6} or {7, 8}.

<image> A row in the airplane

Daenerys Targaryen wants to place her army in the plane so that there are no two soldiers from different groups sitting on neighboring seats.

Your task is to determine if there is a possible arranging of her army in the airplane such that the condition above is satisfied.

Input

The first line contains two integers n and k (1 ≤ n ≤ 10000, 1 ≤ k ≤ 100) — the number of rows and the number of groups of soldiers, respectively.

The second line contains k integers a1, a2, a3, ..., ak (1 ≤ ai ≤ 10000), where ai denotes the number of soldiers in the i-th group.

It is guaranteed that a1 + a2 + ... + ak ≤ 8·n.

Output

If we can place the soldiers in the airplane print "YES" (without quotes). Otherwise print "NO" (without quotes).

You can choose the case (lower or upper) for each letter arbitrary.

Examples

Input

2 2
5 8

Output

YES

Input

1 2
7 1

Output

NO

Input

1 2
4 4

Output

YES

Input

1 4
2 2 1 2

Output

YES

Note

In the first sample, Daenerys can place the soldiers like in the figure below:

<image>

In the second sample, there is no way to place the soldiers in the plane since the second group soldier will always have a seat neighboring to someone from the first group.

In the third example Daenerys can place the first group on seats (1, 2, 7, 8), and the second group an all the remaining seats.

In the fourth example she can place the first two groups on seats (1, 2) and (7, 8), the third group on seats (3), and the fourth group on seats (5, 6).

```python
n,m=map(int,input().split())
l=list(map(int,input().split()))
p=n
for i in range(m) :
    b=l[i]//4
    l[i]=l[i]-4*min(p,l[i]//4)
    p=p-min(p,b)

p1=n*2
for i in range(m) :
    b=l[i]//2
    l[i]=l[i]-2*min(p1,l[i]//2)
    p1=p1-min(p1,b)
p2=p+p1
p3=p
for i in range(m) :
    b=l[i]//2
    l[i]=l[i]-2*min(p2,l[i]//2)
    p2=p2-min(p2,b)
k=0
p3+=p2
for i in range(m) :
    k=k+l[i]
if k>p3 :
    print('NO')
else :
    print('YES')

```


859_E. Desk Disorder

A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.

How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.

Input

Input will begin with a line containing N (1 ≤ N ≤ 100000), the number of engineers.

N lines follow, each containing exactly two integers. The i-th line contains the number of the current desk of the i-th engineer and the number of the desk the i-th engineer wants to move to. Desks are numbered from 1 to 2·N. It is guaranteed that no two engineers sit at the same desk.

Output

Print the number of possible assignments, modulo 1000000007 = 109 + 7.

Examples

Input

4
1 5
5 2
3 7
7 3

Output

6

Input

5
1 10
2 10
3 10
4 10
5 5

Output

5

Note

These are the possible assignments for the first example:

  * 1 5 3 7
  * 1 2 3 7
  * 5 2 3 7
  * 1 5 7 3
  * 1 2 7 3
  * 5 2 7 3

```python
n = int(input())
m = 2 * n + 1
u = [[] for i in range(m)]
v = [0] * m
s = [0] * m
d = 10 ** 9 + 7
y = 1

for j in range(n):
    a, b = map(int, input().split())
    v[a] = b
    if a != b:
        s[b] += 1
        u[b].append(a)

for b in range(m):
    if not v[b]:
        x = 0
        p = [b]
        while p:
            x += 1
            a = p.pop()
            s[a] = -1
            p += u[a]
        y = (x * y) % d

for a in range(m):
    if s[a] == 0:
        b = v[a]
        while s[b] == 1:
            s[b] = -1
            b = v[b]
        s[b] -= 1

for a in range(m):
    if s[a] == 1:
        y = (2 * y) % d
        while s[a]:
            s[a] = 0
            a = v[a]

print(y)
```


884_D. Boxes And Balls

Ivan has n different boxes. The first of them contains some balls of n different colors.

Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.

In order to do this, Ivan will make some turns. Each turn he does the following:

  1. Ivan chooses any non-empty box and takes all balls from this box;
  2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.

The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.

Help Ivan to determine the minimum possible penalty of the game!

Input

The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.

The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.

Output

Print one number — the minimum possible penalty of the game.

Examples

Input

3
1 2 3

Output

6

Input

4
2 3 4 5

Output

19

Note

In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.

In the second example you make two turns:

  1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
  2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.

Total penalty is 19.

```python
from heapq import *
n = int(input())
a = list(map(int, input().split()))
heap = []
res = 0
for i in range(n):
    heappush(heap, a[i])
if n % 2 == 0:
    heappush(heap, 0)
while n > 1:
    cur = heappop(heap)
    cur += heappop(heap)
    cur += heappop(heap)
    res += cur
    heappush(heap, cur)
    n -= 2
print(res)
```


908_F. New Year and Rainbow Roads

Roy and Biv have a set of n points on the infinite number line.

Each point has one of 3 colors: red, green, or blue.

Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.

They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).

However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.

Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).

Help them compute the minimum cost way to choose edges to satisfy the above constraints.

Input

The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points.

The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.

Output

Print a single integer, the minimum cost way to solve the problem.

Examples

Input

4
1 G
5 R
10 B
15 G

Output

23

Input

4
1 G
2 R
3 B
10 G

Output

12

Note

In the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively.

```python
def F1():

    n = int(input())

    ans = 0
    allc = 0
    bigr = 0
    bigb = 0
    lastr = -1
    lastb = -1
    lastg = -(1 << 60)

    for i in range(n):
        x = input().split()
        pos, col = int(x[0]), x[1]

        if col == 'R' or col == 'G':
            if lastr != -1:
                bigr = max(bigr, pos - lastr)
                allc += pos - lastr
            lastr = pos
        if col == 'B' or col == 'G':
            if lastb != -1:
                bigb = max(bigb, pos - lastb)
                allc += pos - lastb
            lastb = pos

        if col == 'G':
            ans += allc + min(0, - bigr - bigb + pos - lastg)
            lastr = lastb = lastg = pos
            bigr = bigb = allc = 0

    ans += allc

    print(ans)
if __name__=='__main__':
    F1()

```


92_E. Ski Base

A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.

In the constructing process m bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The i-th road connects the junctions with numbers ai and bi.

Track is the route with the following properties:

  * The route is closed, that is, it begins and ends in one and the same junction.
  * The route contains at least one road.
  * The route doesn't go on one road more than once, however it can visit any junction any number of times.

Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.

Two ski bases are considered different if they consist of different road sets.

After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem.

Input

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). They represent the number of junctions and the number of roads correspondingly. Then on m lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of the connected junctions. There could be more than one road between a pair of junctions.

Output

Print m lines: the i-th line should represent the number of ways to build a ski base after the end of construction of the road number i. The numbers should be printed modulo 1000000009 (109 + 9).

Examples

Input

3 4
1 3
2 3
1 2
1 2

Output

0
0
1
3

Note

Let us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this:

<image>

The land lot for the construction will look in the following way:

<image>

We can choose a subset of roads in three ways:

<image>

In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1.

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

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

class UnionFind(object):
    __slots__ = ['nodes']

    def __init__(self, n: int):
        self.nodes = [-1] * n

    def find(self, x: int) -> int:
        if self.nodes[x] < 0:
            return x
        else:
            self.nodes[x] = self.find(self.nodes[x])
            return self.nodes[x]

    def unite(self, x: int, y: int) -> bool:
        root_x, root_y, nodes = self.find(x), self.find(y), self.nodes

        if root_x != root_y:
            if nodes[root_x] > nodes[root_y]:
                root_x, root_y = root_y, root_x
            nodes[root_x] += nodes[root_y]
            nodes[root_y] = root_x

        return root_x != root_y

if __name__ == '__main__':
    n, m = map(int, input().split())
    uf = UnionFind(n + 10)
    ans = [0] * m
    x = 1
    mod = 10**9 + 9

    for i, (u, v) in enumerate(map(int, input().split()) for _ in range(m)):
        if not uf.unite(u, v):
            x = x * 2 % mod
        ans[i] = (x - 1) % mod

    sys.stdout.buffer.write('\n'.join(map(str, ans)).encode('utf-8'))

```


958_C1. Encryption (easy)

Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.

Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:

Define the score of X to be the sum of the elements of X modulo p.

Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:

  * Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
  * The two parts do not overlap.
  * The total sum S of the scores of those two parts is maximized. This is the encryption code.

Output the sum S, which is the encryption code.

Input

The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.

The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].

Output

Output the number S as described in the problem statement.

Examples

Input

4 10
3 4 7 2

Output

16

Input

10 12
16 3 24 13 9 8 7 5 12 12

Output

13

Note

In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.

In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>.

```python
n,p = map(int,input().split())
a  = list(map(int,input().split()))
forward = [a[0]]
for i in range(1,n):
    forward.append(forward[-1] + a[i])
sm = sum(a)
mx = -float('inf')
for i in range(n-1):
    mx = max(mx,(forward[i]%p) + ((sm -forward[i] )%p))
print(mx)
```


p02568 AtCoder Library Practice Contest - Range Affine Range Sum

You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.

* `0 l r b c`: For each i = l, l+1, \dots, {r - 1}, set a_i \gets b \times a_i + c.
* `1 l r`: Print \sum_{i = l}^{r - 1} a_i \bmod 998244353.

Constraints

* 1 \leq N, Q \leq 500000
* 0 \leq a_i, c < 998244353
* 1 \leq b < 998244353
* 0 \leq l < r \leq N
* All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
a_0 a_1 ... a_{N - 1}
\textrm{Query}_0
\textrm{Query}_1
:
\textrm{Query}_{Q - 1}

Output

For each query of the latter type, print the answer.

Example

Input

5 7
1 2 3 4 5
1 0 5
0 2 4 100 101
1 0 3
0 1 3 102 103
1 2 5
0 2 5 104 105
1 0 5

Output

15
404
41511
4317767

```python
#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def R(n): return [sys.stdin.readline().strip() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]

def perm(n, r): return math.factorial(n) // math.factorial(r)
def comb(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n-r))

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if len(args) > 0 else [default for _ in range(n)]

dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD = 998244353
INF = float("inf")

sys.setrecursionlimit(1000000)

# モノイドに対して適用可能、Nが2冪でなくても良い
#
class LazySegTree():
    def __init__(self, initial_values, monoid_func, composition, operate, monoid_identity, operator_identity):
        self.N = len(initial_values)
        self.monoid_func = monoid_func
        self.composition = composition # composition(f, g) => g(f(x))の順であることに注意
        self.operate = operate #右作用 operate(a, f) => f(a), 雑に可換な処理を書こうとするとバグるので注意
        self.monoid_identity = monoid_identity
        self.operator_identity = operator_identity
        self.data = [self.monoid_identity]*(2*self.N)
        self.lazy = [self.operator_identity]*(2*self.N)
        self.size = [0]*(2*self.N)

        for i, ai in enumerate(initial_values):
            self.data[self.N+i] = ai
            self.size[self.N+i] = 1
        for i in range(self.N-1,0,-1):
            self.data[i] = self.monoid_func(self.data[i << 1], self.data[i << 1 | 1])
            self.size[i] = self.size[i << 1] + self.size[i << 1 | 1]

    def update(self,i,x):  # i番目(0-index)の値をxに変更
        i += self.N
        self.data[i] = x
        while i>1:
            i >>= 1
            self.data[i] = self.monoid_func(self.data[i << 1], self.data[i << 1 | 1])

    def eval_at(self,i):  # i番目で作用を施した値を返す
        return self.operate(self.data[i],self.lazy[i],self.size[i])

    def eval_above(self,i):  # i番目より上の値を再計算する
        while i > 1:
            i >>= 1
            self.data[i] = self.monoid_func(self.eval_at(i << 1),self.eval_at(i << 1 | 1))

    def propagate_at(self,i):  # i番目で作用を施し、1つ下に作用の情報を伝える
        self.data[i] = self.operate(self.data[i],self.lazy[i],self.size[i])
        self.lazy[i << 1] = self.composition(self.lazy[i << 1],self.lazy[i])
        self.lazy[i << 1 | 1] = self.composition(self.lazy[i << 1 | 1], self.lazy[i])
        self.lazy[i] = self.operator_identity

    def propagate_above(self,i):  # i番目より上で作用を施す
        H = i.bit_length()
        for h in range(H,0,-1):
            self.propagate_at(i >> h)

    def fold(self, L, R):  # [L,R)の区間取得
        L += self.N
        R += self.N
        L0 = L // (L & -L)
        R0 = R // (R & -R) - 1
        self.propagate_above(L0)
        self.propagate_above(R0)
        vL = self.monoid_identity
        vR = self.monoid_identity
        while L < R:
            if L & 1:
                vL = self.monoid_func(vL,self.eval_at(L))
                L += 1
            if R & 1:
                R -= 1
                vR = self.monoid_func(self.eval_at(R),vR)
            L >>= 1
            R >>= 1
        return self.monoid_func(vL,vR)

    #重たい
    def apply_range(self,L,R,x):  # [L,R)にxを作用
        L += self.N
        R += self.N
        L0 = L // (L & -L)
        R0 = R // (R & -R) - 1
        self.propagate_above(L0)
        self.propagate_above(R0)
        while L < R:
            if L & 1:
                self.lazy[L] = self.composition(self.lazy[L], x)
                L += 1
            if R & 1:
                R -= 1
                self.lazy[R] = self.composition(self.lazy[R], x)
            L >>= 1
            R >>= 1
        self.eval_above(L0)
        self.eval_above(R0)

# shift = 1 << 32
# mask = (1 << 32) - 1

def monoid_func(s, t):
    sv, sn = s >> 32, s % (1 << 32)
    tv, tn = t >> 32, t % (1 << 32)
    return (((sv + tv) % MOD) << 32) + sn + tn

# g(f(x))の順であることに注意
def composition(f, g):
    fb, fc = f >> 32, f % (1 << 32)
    gb, gc = g >> 32, g % (1 << 32)
    return ((fb * gb % MOD) << 32) + ((gb * fc + gc) % MOD)

#右作用
#雑に可換な処理を書こうとするとバグるので注意
def operate(a,f,_):
    fb, fc = f >> 32, f % (1 << 32)
    av, an = a >> 32, a % (1 << 32)
    return (((fb * av + fc * an) % MOD) << 32) + an

def main():
    monoid_identity = 0
    operator_identity = 1 << 32

    N, Q = LI()
    A = [(ai << 32) + 1 for ai in LI()]
    LST = LazySegTree(A, monoid_func, composition, operate, monoid_identity, operator_identity)

    for q in LIR(Q):
        if q[0] == 0:
            _, l, r, b, c = q
            LST.apply_range(l,r,(b<<32)+c)
        else:
            _, l, r = q
            print(LST.fold(l,r) >> 32)

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


p02699 AtCoder Beginner Contest 164 - Sheep and Wolves

There are S sheep and W wolves.

If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.

If the wolves will attack the sheep, print `unsafe`; otherwise, print `safe`.

Constraints

* 1 \leq S \leq 100
* 1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

If the wolves will attack the sheep, print `unsafe`; otherwise, print `safe`.

Examples

Input

4 5

Output

unsafe

Input

100 2

Output

safe

Input

10 10

Output

unsafe

```python
s,w = map(int, input().split())
print("safe" if w<s else "unsafe")
```


p02965 AtCoder Grand Contest 036 - GP 2

We have a sequence of N integers: x=(x_0,x_1,\cdots,x_{N-1}). Initially, x_i=0 for each i (0 \leq i \leq N-1).

Snuke will perform the following operation exactly M times:

* Choose two distinct indices i, j (0 \leq i,j \leq N-1,\ i \neq j). Then, replace x_i with x_i+2 and x_j with x_j+1.

Find the number of different sequences that can result after M operations. Since it can be enormous, compute the count modulo 998244353.

Constraints

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

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of different sequences that can result after M operations, modulo 998244353.

Examples

Input

2 2

Output

3

Input

3 2

Output

19

Input

10 10

Output

211428932

Input

100000 50000

Output

3463133


p03248 AtCoder Regular Contest 103 - Tr/ee

You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?

* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by removing one edge from the tree.
* If the i-th character in s is `0`, we cannot have a connected component of size i by removing any one edge from the tree.

If such a tree exists, construct one such tree.

Constraints

* 2 \leq n \leq 10^5
* s is a string of length n consisting of `0` and `1`.

Input

Input is given from Standard Input in the following format:

s

Output

If a tree with n vertices that satisfies the conditions does not exist, print `-1`.

If a tree with n vertices that satisfies the conditions exist, print n-1 lines. The i-th line should contain u_i and v_i with a space in between. If there are multiple trees that satisfy the conditions, any such tree will be accepted.

Examples

Input

1111

Output

-1

Input

1110

Output

1 2
2 3
3 4

Input

1010

Output

1 2
1 3
1 4

```python
def die(): print(-1); exit()

s = input()
n = len(s)
if s[-1] == '1': die()
if s[0] == '0': die()
for i in range(n-1):
    if s[i] != s[-i-2]: die()

root = last = 1
for i in range(n-1):
    last+= 1
    print(root, last)
    if s[i] == '1': root = last
```


p03399 AtCoder Beginner Contest 092 - Traveling Budget

You planned a trip using trains and buses. The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket. Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

* 1 \leq A \leq 1 000
* 1 \leq B \leq 1 000
* 1 \leq C \leq 1 000
* 1 \leq D \leq 1 000
* All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Examples

Input

600
300
220
420

Output

520

Input

555
555
400
200

Output

755

Input

549
817
715
603

Output

1152

```python
A = [int(input()) for i in range(4)]
print(min(A[0],A[1]) + min(A[2],A[3]))
```


p03564 AtCoder Beginner Contest 076 - Addition and Multiplication

Square1001 has seen an electric bulletin board displaying the integer 1. He can perform the following operations A and B to change this value:

* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.

Square1001 needs to perform these operations N times in total. Find the minimum possible value displayed in the board after N operations.

Constraints

* 1 \leq N, K \leq 10
* All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the minimum possible value displayed in the board after N operations.

Examples

Input

4
3

Output

10

Input

10
10

Output

76

```python
n=int(input())
k=int(input())
s=1
for i in range(n): s=min(s+k, s*2)
print(s)
```


p03719 AtCoder Beginner Contest 061 - Between Two Integers

You are given three integers A, B and C. Determine whether C is not less than A and not greater than B.

Constraints

* -100≤A,B,C≤100
* A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print `Yes`; otherwise, print `No`.

Examples

Input

1 3 2

Output

Yes

Input

6 5 4

Output

No

Input

2 2 2

Output

Yes

```python
a,b,c=map(int,input().split());print('YNeos'[a>c or b<c::2])
```


p03879 CODE FESTIVAL 2016 Grand Final(Parallel) - Inscribed Bicycle

Snuke received a triangle as a birthday present. The coordinates of the three vertices were (x_1, y_1), (x_2, y_2), and (x_3, y_3).

He wants to draw two circles with the same radius inside the triangle such that the two circles do not overlap (but they may touch). Compute the maximum possible radius of the circles.

Constraints

* 0 ≤ x_i, y_i ≤ 1000
* The coordinates are integers.
* The three points are not on the same line.

Input

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

x_1 y_1
x_2 y_2
x_3 y_3

Output

Print the maximum possible radius of the circles. The absolute error or the relative error must be at most 10^{-9}.

Examples

Input

0 0
1 1
2 0

Output

0.292893218813

Input

3 1
1 5
4 9

Output

0.889055514217

```python
from math import hypot

x1, y1, x2, y2, x3, y3 = map(int, open(0).read().split())

a = hypot(x1 - x2, y1 - y2)
b = hypot(x2 - x3, y2 - y3)
c = hypot(x3 - x1, y3 - y1)
R = abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / (a + b + c)
m = max(a, b, c)
r = m / (2 + m / R)

print("{:.12f}".format(r))

```


p04040 AtCoder Regular Contest 058 - Iroha and a Grid

We have a large square grid with H rows and W columns. Iroha is now standing in the top-left cell. She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.

However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.

Find the number of ways she can travel to the bottom-right cell.

Since this number can be extremely large, print the number modulo 10^9+7.

Constraints

* 1 ≦ H, W ≦ 100,000
* 1 ≦ A < H
* 1 ≦ B < W

Input

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

H W A B

Output

Print the number of ways she can travel to the bottom-right cell, modulo 10^9+7.

Examples

Input

2 3 1 1

Output

2

Input

10 7 3 4

Output

3570

Input

100000 100000 99999 99999

Output

1

Input

100000 100000 44444 55555

Output

738162020

```python
from sys import stdin, stdout, stderr, setrecursionlimit
from functools import lru_cache

setrecursionlimit(10**7)

mod = 10**9 + 7

def solve():
    def binom(n, k):
        res = (modfact[n] * factinv[k]) % mod
        res = (res * factinv[n - k]) % mod
        return res

    h, w, a, b = map(int, input().split())
    ans = 0
    modfact = [1] * (h + w)
    factinv = [1] * (h + w)

    for i in range(1, h + w):
        modfact[i] = (i * modfact[i - 1]) % mod
        factinv[i] = (pow(i, mod - 2, mod) * factinv[i - 1]) % mod

    for i in range(h - a):
        ans += (binom(b + i - 1, i) * binom(w + h - b - i - 2, h - i - 1)) % mod
        ans %= mod

    print(ans)

'''
@lru_cache(maxsize=None)
def binom(n, k):
    res = (modfact(n) * factinv(k)) % mod
    res = (res * factinv(n - k)) % mod
    return res

@lru_cache(maxsize=None)
def modfact(n):
    if n == 0:
        return 1

    return (n * modfact(n - 1)) % mod

@lru_cache(maxsize=None)
def factinv(n):
    if n == 0:
        return 1

    return (pow(n, mod - 2, mod) * factinv(n - 1)) % mod
'''

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


p00121 Seven Puzzle

The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.

7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.

The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).

The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.

<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6

<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)

Input

Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.

Output

For each puzzle, output the minimum number of steps to move to the final state on one line.

Example

Input

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

Output

0
1
28

```python
from collections import deque
import copy

swap = [[1, 4], [0, 2, 5], [1, 3, 6], [2, 7], [0, 5], [1, 4, 6], [2, 5, 7], [3, 6]]

def bfs():
    ia = list(range(8))
    count = {str(ia): 0}
    que = deque()
    que.append((ia, 0))
    while len(que) != 0:
        state, cnt = que.popleft()
        # pos:0?????????
        pos = state.index(0)
        swap_target = swap[pos]
        for i in swap_target:
            tmp_state = copy.copy(state)
            tmp_state[i], tmp_state[pos] = tmp_state[pos], tmp_state[i]
            if str(tmp_state) not in count:
                count[str(tmp_state)] = cnt + 1
                que.append((tmp_state, cnt + 1))
    return count

if __name__ == '__main__':
    count = bfs()
    while True:
        try:
            prob = list(map(int, input().split()))
            print(count[str(prob)])
        except:
            break
```


p00254 All Numbers Lead to 6174

Do the following for a four-digit number N consisting of numbers 0-9.

1. Let L be the number obtained as a result of arranging the numerical values of each of the N digits in descending order.
2. Let S be the number obtained as a result of arranging the numerical values of each of the N digits in ascending order.
3. Let the difference L-S be the new N (end of one operation)
4. Repeat from 1. for the new N

At this time, it is known that any four-digit number will eventually become 6174, unless all digits are the same number (0000, 1111, etc.). For example, when N = 2012
First time (N = 2012): L = 2210, S = 0122, L-S = 2088
Second time (N = 2088): L = 8820, S = 0288, L-S = 8532
Third time (N = 8532): L = 8532, S = 2358, L-S = 6174
And reach 6174 in 3 operations.

Write a program that calculates how many operations will reach 6174 given a four-digit number consisting of the numbers 0-9.

input

The input consists of multiple datasets. The end of the input is indicated by 0000 on one line. Each dataset is given in the following format:

N

The dataset is one line and N (1 ≤ N ≤ 9999) indicates a four-digit number. If N <1000, the upper digit is padded with zeros.

The number of datasets does not exceed 10000.

output

The number of operations to reach 6174 for each data set is output on one line. However, if a number with all the same digits is given as input, NA is output.

Example

Input

6174
2012
3333
0000

Output

0
3
NA

```python
while True:
    number=int(input())
    if number==0000:
            break
    trial=0
    while True:
        if number==6174:
            print(trial)
            break
        box=[]
        for i in range(4):
            a=number%10
            number=int(number/10)
            box.append(a)
        if box[0]==box[1] and box[2]==box[3] and box[1]==box[2]:
            print("NA")
            break
        box.sort()
        l=0

        for i in range(4):
            l+=box[i]*10**i
        box.sort(reverse=True)
        s=0
        for i in range(4):
            s+=box[i]*10**i
        number=l-s
        trial+=1

```


p00440 Longest Steps

problem

There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.

Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.

input

The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.

On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.

Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.

The number of datasets does not exceed 5.

output

Outputs an integer on one line for each dataset.

Examples

Input

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

Output

2
4

Input

None

Output

None

```python
anss = []
flag = False
def main():
    N, K = [int(i) for i in input().split()]
    if N == K == 0:
        global flag
        flag = True
        return
    A = [int(input()) for _ in range(K)]
    A.sort()
    zero = False
    if A[0] == 0:
        zero = True
    prev = -1
    last_island = -1
    current_streak = 0
    ans = 0
    for a in A:
        if prev == -1 or a == prev + 1:
            current_streak += 1
        elif zero == True and a == prev + 2:
            last_island = current_streak
            current_streak = 1
        else:
            last_island = -1
            current_streak = 1
        ans = max(current_streak + last_island + 1, ans)
        prev = a
    global anss
    anss.append(ans)
while not flag:
    main()
for a in anss:
    print(a)

```


p00631 Split Up!

Brave Ponta and his best friend, Brave Gonta, have come to Luida's bar in search of friends to embark on an epic adventure. There are many warriors, monks and wizards in the tavern who are itching to go on an adventure.

Gonta, who is kind-hearted, cared for Ponta and said, "You can choose your friends first."

On the other hand, don't worry about Ponta and Gonta. "No, you can choose first."

We continued to give in to each other, and finally Luida proposed: "Then, I'll divide the n registrants here with this" party division machine "so that the total fighting power of each party is as even as possible."

The task given to you is to create a program that is built into the partying machine.

This program inputs n integers and outputs the minimum difference between the total value of the integers contained in A and the total value of the integers contained in B when they are divided into two groups A and B. Must be.

Thanks to this machine, Ponta and Gonta got along well and went on an epic adventure ...

Input

Multiple datasets are given as input. Each dataset is given in the following format:

n (number of registrants: integer)
a1 a2 ... an (combat power of each registrant: blank-separated integer)

n is 20 or less, and each registrant's combat power does not exceed 1 million.

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

Output

Print the minimum value on one line for each dataset.

Example

Input

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

Output

1
1

```python
def main():
  while True:
    n = int(input())
    if n == 0:
      break
    alst = list(map(int, input().split()))
    s = sum(alst)
    alst = [a * 2 for a in alst]
    lst = [-s]
    for a in alst:
      lst.extend([i + a for i in lst])
    print(min(map(abs, lst)))
main()

```