1427_C. The Hard Work of Paparazzi

You are a paparazzi working in Manhattan.

Manhattan has r south-to-north streets, denoted by numbers 1, 2,…, r in order from west to east, and r west-to-east streets, denoted by numbers 1,2,…,r in order from south to north. Each of the r south-to-north streets intersects each of the r west-to-east streets; the intersection between the x-th south-to-north street and the y-th west-to-east street is denoted by (x, y). In order to move from the intersection (x,y) to the intersection (x', y') you need |x-x'|+|y-y'| minutes.

You know about the presence of n celebrities in the city and you want to take photos of as many of them as possible. More precisely, for each i=1,..., n, you know that the i-th celebrity will be at the intersection (x_i, y_i) in exactly t_i minutes from now (and he will stay there for a very short time, so you may take a photo of him only if at the t_i-th minute from now you are at the intersection (x_i, y_i)). You are very good at your job, so you are able to take photos instantaneously. You know that t_i < t_{i+1} for any i=1,2,…, n-1.

Currently you are at your office, which is located at the intersection (1, 1). If you plan your working day optimally, what is the maximum number of celebrities you can take a photo of?

Input

The first line of the input contains two positive integers r, n (1≤ r≤ 500, 1≤ n≤ 100,000) – the number of south-to-north/west-to-east streets and the number of celebrities.

Then n lines follow, each describing the appearance of a celebrity. The i-th of these lines contains 3 positive integers t_i, x_i, y_i (1≤ t_i≤ 1,000,000, 1≤ x_i, y_i≤ r) — denoting that the i-th celebrity will appear at the intersection (x_i, y_i) in t_i minutes from now.

It is guaranteed that t_i<t_{i+1} for any i=1,2,…, n-1.

Output

Print a single integer, the maximum number of celebrities you can take a photo of.

Examples

Input

10 1
11 6 8

Output

0

Input

6 9
1 2 6
7 5 1
8 5 5
10 3 1
12 4 4
13 6 2
17 6 6
20 1 4
21 5 4

Output

4

Input

10 4
1 2 1
5 10 9
13 8 8
15 9 9

Output

1

Input

500 10
69 477 122
73 186 235
341 101 145
372 77 497
390 117 440
494 471 37
522 300 498
682 149 379
821 486 359
855 157 386

Output

3

Note

Explanation of the first testcase: There is only one celebrity in the city, and he will be at intersection (6,8) exactly 11 minutes after the beginning of the working day. Since you are initially at (1,1) and you need |1-6|+|1-8|=5+7=12 minutes to reach (6,8) you cannot take a photo of the celebrity. Thus you cannot get any photo and the answer is 0.

Explanation of the second testcase: One way to take 4 photos (which is the maximum possible) is to take photos of celebrities with indexes 3, 5, 7, 9 (see the image for a visualization of the strategy):

  * To move from the office at (1,1) to the intersection (5,5) you need |1-5|+|1-5|=4+4=8 minutes, so you arrive at minute 8 and you are just in time to take a photo of celebrity 3.
  * Then, just after you have taken a photo of celebrity 3, you move toward the intersection (4,4). You need |5-4|+|5-4|=1+1=2 minutes to go there, so you arrive at minute 8+2=10 and you wait until minute 12, when celebrity 5 appears.
  * Then, just after you have taken a photo of celebrity 5, you go to the intersection (6,6). You need |4-6|+|4-6|=2+2=4 minutes to go there, so you arrive at minute 12+4=16 and you wait until minute 17, when celebrity 7 appears.
  * Then, just after you have taken a photo of celebrity 7, you go to the intersection (5,4). You need |6-5|+|6-4|=1+2=3 minutes to go there, so you arrive at minute 17+3=20 and you wait until minute 21 to take a photo of celebrity 9.

<image>

Explanation of the third testcase: The only way to take 1 photo (which is the maximum possible) is to take a photo of the celebrity with index 1 (since |2-1|+|1-1|=1, you can be at intersection (2,1) after exactly one minute, hence you are just in time to take a photo of celebrity 1).

Explanation of the fourth testcase: One way to take 3 photos (which is the maximum possible) is to take photos of celebrities with indexes 3, 8, 10:

  * To move from the office at (1,1) to the intersection (101,145) you need |1-101|+|1-145|=100+144=244 minutes, so you can manage to be there when the celebrity 3 appears (at minute 341).
  * Then, just after you have taken a photo of celebrity 3, you move toward the intersection (149,379). You need |101-149|+|145-379|=282 minutes to go there, so you arrive at minute 341+282=623 and you wait until minute 682, when celebrity 8 appears.
  * Then, just after you have taken a photo of celebrity 8, you go to the intersection (157,386). You need |149-157|+|379-386|=8+7=15 minutes to go there, so you arrive at minute 682+15=697 and you wait until minute 855 to take a photo of celebrity 10.

```python
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------

import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading

#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)

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")

#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
    def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

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

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

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

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

    def __len__(self):
        return self._len

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

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

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

class SegmentTree1:
    def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

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

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

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

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

    def __len__(self):
        return self._len

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

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

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

MOD=10**9+7
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

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

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

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

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

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(200001)]
pp=[0]*200001
def SieveOfEratosthenes(n=200000):

    # Create a boolean array "prime[0..n]" and initialize
    #  all entries it as true. A value in prime[i] will
    # finally be false if i is Not a prime, else true.

    p = 2
    while (p * p <= n):

        # If prime[p] is not changed, then it is a prime
        if (prime[p] == True):

            # Update all multiples of p
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
#---------------------------------running code------------------------------------------
r, n = map(int, input().split())
M = 2 * r

A = [(0, 1, 1)] + [tuple(map(int, input().split())) for _ in range(n)]
DP = [-n] * (n+1)
DP[0] = 0

ii = 0
besti = -n

for i in range(1, n+1):
	t, x, y = A[i]

	while A[ii][0] + M <= t:
		besti = max(besti, DP[ii])
		ii += 1

	b = besti+1

	j = i
	while j > 0:
		j -= 1
		to, xo, yo = A[j]

		if DP[j] >= b and abs(xo - x) + abs(yo - y) <= t - to:
			b = DP[j] + 1

		if t - to >= M: break

	DP[i] = b

print(max(DP))
```


1450_C1. Errich-Tac-Toe (Easy Version)

The only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.

Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.

In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell of the grid is either empty or contains a token. There are two types of tokens: X and O. If there exist three tokens of the same type consecutive in a row or column, it is a winning configuration. Otherwise, it is a draw configuration.

<image> The patterns in the first row are winning configurations. The patterns in the second row are draw configurations.

In an operation, you can change an X to an O, or an O to an X. Let k denote the total number of tokens in the grid. Your task is to make the grid a draw in at most ⌊ k/3⌋ (rounding down) operations.

You are not required to minimize the number of operations.

Input

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

The first line of each test case contains a single integer n (1≤ n≤ 300) — the size of the grid.

The following n lines each contain a string of n characters, denoting the initial grid. The character in the i-th row and j-th column is '.' if the cell is empty, or it is the type of token in the cell: 'X' or 'O'.

It is guaranteed that not all cells are empty.

In the easy version, the character 'O' does not appear in the input.

The sum of n across all test cases does not exceed 300.

Output

For each test case, print the state of the grid after applying the operations.

We have proof that a solution always exists. If there are multiple solutions, print any.

Example

Input

3
3
.X.
XXX
.X.
6
XX.XXX
XXXXXX
XXX.XX
XXXXXX
XX.X.X
XXXXXX
5
XXX.X
.X..X
XXX.X
..X..
..X..

Output

.X.
XOX
.X.
XX.XXO
XOXXOX
OXX.XX
XOOXXO
XX.X.X
OXXOXX
XOX.X
.X..X
XXO.O
..X..
..X..

Note

In the first test case, there are initially three 'X' consecutive in the second row and the second column. By changing the middle token to 'O' we make the grid a draw, and we only changed 1≤ ⌊ 5/3⌋ token.

In the second test case, we change only 9≤ ⌊ 32/3⌋ tokens, and there does not exist any three 'X' or 'O' consecutive in a row or column, so it is a draw.

In the third test case, we change only 3≤ ⌊ 12/3⌋ tokens, and the resulting grid is a draw.

```python

def disti(b,ind):

	a=[]
	for i in b:
		h=[]
		for j in i: h.append(j)
		a.append(h)
	ans=0

	id=0

	for i in range(n):
		start = ind[id%3]
		id+=1
		for j in range(start ,n,3):

			left=''
			right=''
			up=''
			down=''
			mid1=''
			mid2=''

			if(j-2 >= 0): left = a[i][j-2] + a[i][j-1] + a[i][j]
			if(j+2 <n ): right = a[i][j+2] + a[i][j+1] + a[i][j]
			if(i+2 <n ): down = a[i+2][j] + a[i+1][j] + a[i][j]
			if(i-2 >= 0 ): up = a[i-2][j] + a[i-1][j] + a[i][j]
			if(i+1<n and i-1>=0) : mid1 = a[i-1][j] + a[i][j] + a[i+1][j]
			if(j+1<n and j-1>=0) : mid2 = a[i][j-1] + a[i][j] + a[i][j+1]

			ok=False
			for k in (left,right,up,down,mid1,mid2):
				if(k=='XXX' or k=='OOO'): ok=True

			# ok=True

			if(ok and a[i][j] == 'X') :
				a[i][j] = 'O'
				ans+=1
			# elif(ok and a[i][j] == 'O') : a[i][j] = 'X'
	return a,ans

def P(b):
	for i in b: print(*i,sep="")

for _ in range(int(input())):

	n=int(input())
	a=[]
	tot=0
	for i in range(n):
		s=list(input())
		a.append(s)
		tot+= (n-s.count('.'))

	b1,s1 = disti(a,[1,0,2])
	b2,s2 = disti(a,[2,1,0])
	b3,s3 = disti(a,[0,2,1])

	if(s1*3 <=tot) : P(b1)
	elif(s2*3 <=tot) : P(b2)
	elif(s3*3 <=tot) : P(b3)
	# print(s1,s2,s3)

```


1474_A. Puzzle From the Future

In the 2022 year, Mike found two binary integers a and b of length n (both of them are written only by digits 0 and 1) that can have leading zeroes. In order not to forget them, he wanted to construct integer d in the following way:

  * he creates an integer c as a result of bitwise summing of a and b without transferring carry, so c may have one or more 2-s. For example, the result of bitwise summing of 0110 and 1101 is 1211 or the sum of 011000 and 011000 is 022000;
  * after that Mike replaces equal consecutive digits in c by one digit, thus getting d. In the cases above after this operation, 1211 becomes 121 and 022000 becomes 020 (so, d won't have equal consecutive digits).

Unfortunately, Mike lost integer a before he could calculate d himself. Now, to cheer him up, you want to find any binary integer a of length n such that d will be maximum possible as integer.

Maximum possible as integer means that 102 > 21, 012 < 101, 021 = 21 and so on.

Input

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

The first line of each test case contains the integer n (1 ≤ n ≤ 10^5) — the length of a and b.

The second line of each test case contains binary integer b of length n. The integer b consists only of digits 0 and 1.

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

Output

For each test case output one binary integer a of length n. Note, that a or b may have leading zeroes but must have the same length n.

Example

Input

5
1
0
3
011
3
110
6
111000
6
001011

Output

1
110
100
101101
101110

Note

In the first test case, b = 0 and choosing a = 1 gives d = 1 as a result.

In the second test case, b = 011 so:

  * if you choose a = 000, c will be equal to 011, so d = 01;
  * if you choose a = 111, c will be equal to 122, so d = 12;
  * if you choose a = 010, you'll get d = 021.
  * If you select a = 110, you'll get d = 121.

We can show that answer a = 110 is optimal and d = 121 is maximum possible.

In the third test case, b = 110. If you choose a = 100, you'll get d = 210 and it's the maximum possible d.

In the fourth test case, b = 111000. If you choose a = 101101, you'll get d = 212101 and it's maximum possible d.

In the fifth test case, b = 001011. If you choose a = 101110, you'll get d = 102121 and it's maximum possible d.

```python
for tc in range(int(input())):
    n = int(input())
    b = input()
    a = ['' for i in range(n)]
    d = ['0' for i in range(n)]
    if b[0] == '0':d[0] = '1'
    else:d[0] = '2'
    for i in range(1,n):
        if b[i] == '0':
            if d[i-1] != '1':
                d[i] = '1'
            else:d[i] = '0'
        if b[i] == '1':
            if d[i-1] == '2':
                d[i] = '1'
            else:d[i] = '2'
    for i in range(n):
        a[i] = str(eval(d[i]+'-'+b[i]))
    print(''.join(a))

```


149_C. Division into Teams

Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).

The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays).

Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:

  * Each boy plays for exactly one team (x + y = n).
  * The sizes of teams differ in no more than one (|x - y| ≤ 1).
  * The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: <image>

Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.

Input

The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.

Output

On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills.

If there are multiple ways to solve the problem, print any of them.

The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.

Examples

Input

3
1 2 1

Output

2
1 2
1
3

Input

5
2 3 3 1 1

Output

3
4 1 3
2
5 2

Note

Let's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.

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

def main():
    pass

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def count1(s):
    c=0
    for i in s:
        if(i=='1'):
            c+=1
    return(c)
def binary(n):
    return(bin(n).replace("0b",""))
def decimal(s):
    return(int(s,2))
def pow2(n):
    p=0
    while(n>1):
        n//=2
        p+=1
    return(p)
def isPrime(n):
    if(n==1):
        return(False)
    else:
        root=int(n**0.5)
        root+=1
        for i in range(2,root):
            if(n%i==0):
                return(False)
        return(True)
n=int(input())
l=list(map(int,input().split()))
pos=[]
for i in range(0,n):
    pos.append([l[i],i+1])
pos.sort()
t1=[]
t2=[]
for i in range(0,n):
    if(i%2==0):
        t1.append(pos[i][1])
    else:
        t2.append(pos[i][1])
print(len(t1))
print(*t1)
print(len(t2))
print(*t2)

```


1523_C. Compression and Expansion

<image>

William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.

A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items a_1  .  a_2  .  a_3  .   ⋅⋅⋅   .\,a_k and can be one of two types:

  1. Add an item a_1  .  a_2  .  a_3  .  ⋅⋅⋅  .  a_k  .  1 (starting a list of a deeper level), or
  2. Add an item a_1  .  a_2  .  a_3  .  ⋅⋅⋅  .  (a_k + 1) (continuing the current level).

Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the "Notes" section.

When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the "Ctrl-S" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.

William wants you to help him restore a fitting original nested list.

Input

Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10). Description of the test cases follows.

The first line of each test case contains a single integer n (1 ≤ n ≤ 10^3), which is the number of lines in the list.

Each of the next n lines contains a single integer a_i (1 ≤ a_i ≤ n), which is what remains of William's nested list.

It is guaranteed that in each test case at least one fitting list exists.

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

Output

For each test case output n lines which represent a valid nested list, which could become the data provided to you by William.

If there are multiple answers, print any.

Example

Input

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

Output

1
1.1
1.2
1.3
1
1.1
1.1.1
1.1.2
1.2
1.2.1
2
2.1
2.2

Note

In the second example test case one example of a fitting list is:

1

1.1

1.1.1

1.1.2

1.2

1.2.1

2

2.1

2.2

This list can be produced by using the sequence of operations shown below: <image>

  1. Original list with a single item 1.
  2. Insert item 2 by using the insertion operation of the second type after item 1.
  3. Insert item 1.1 by using the insertion operation of the first type after item 1.
  4. Insert item 1.2 by using the insertion operation of the second type after item 1.1.
  5. Insert item 1.1.1 by using the insertion operation of the first type after item 1.1.
  6. Insert item 1.1.2 by using the insertion operation of the second type after item 1.1.1.
  7. Insert item 1.2.1 by using the insertion operation of the first type after item 1.2.
  8. Insert item 2.1 by using the insertion operation of the first type after item 2.
  9. Insert item 2.2 by using the insertion operation of the second type after item 2.1.

```python
import sys
T = int(sys.stdin.readline().strip())
for t in range (0, T):
    n = int(sys.stdin.readline().strip())
    x = int(sys.stdin.readline().strip())
    ans = [[x]]
    for i in range (0, n - 1):
        x = int(sys.stdin.readline().strip())
        ans.append(ans[-1][:])
        if x == 1:
            ans[-1].append(x)
        else:
            while x != ans[-1][-1] + 1:
                ans[-1].pop()
            ans[-1][-1] = ans[-1][-1] + 1
    for x in ans:
        print(".".join(list(map(str, x))))
```


155_B. Combination

Ilya plays a card game by the following rules.

A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.

More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.

Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?

Input

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has.

Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly.

Output

Print the single number — the maximum number of points you can score in one round by the described rules.

Examples

Input

2
1 0
2 0

Output

2

Input

3
1 0
2 0
0 2

Output

3

Note

In the first sample none of two cards brings extra moves, so you should play the one that will bring more points.

In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.

```python
n=int(input())
arr=[]
for i in range(n):
	a,b=map(int,input().split())
	arr.append((b,a))
arr.sort(reverse=True)
counter=1
ans=0
i=0
while(counter and i<n):
	counter-=1
	counter+=arr[i][0]
	ans+=arr[i][1]
	i+=1
print(ans)

```


177_C2. Party

To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.

More formally, for each invited person the following conditions should be fulfilled:

  * all his friends should also be invited to the party;
  * the party shouldn't have any people he dislikes;
  * all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2, a3, ..., ap - 1 such that all pairs of people ai and ai + 1 (1 ≤ i < p) are friends.

Help the Beaver find the maximum number of acquaintances he can invite.

Input

The first line of input contains an integer n — the number of the Beaver's acquaintances.

The second line contains an integer k <image> — the number of pairs of friends. Next k lines contain space-separated pairs of integers ui, vi <image> — indices of people who form the i-th pair of friends.

The next line contains an integer m <image> — the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described.

Each pair of people is mentioned in the input at most once <image>. In particular, two persons cannot be friends and dislike each other at the same time.

The input limitations for getting 30 points are:

  * 2 ≤ n ≤ 14

The input limitations for getting 100 points are:

  * 2 ≤ n ≤ 2000

Output

Output a single number — the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.

Examples

Input

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

Output

3

Note

Let's have a look at the example.

<image>

Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).

```python
from collections import defaultdict

def Root(child):
    while(Parent[child]!=child):
        child = Parent[child]
    return child

def Union(a,b):
    root_a = Root(a)
    root_b = Root(b)

    if(root_a!=root_b):
        if(Size[root_a]<Size[root_b]):
            Parent[root_a] = root_b
            Size[root_b]+=Size[root_a]
        else:
            Parent[root_b] = root_a
            Size[root_a]+=Size[root_b]
        return 1

    return 0

n = int(input())
Parent = [i for i in range(n)]
Size   = [1 for i in range(n)]

k = int(input())
for i in range(k):
    u,v = map(int,input().split())
    u-=1;v-=1
    Union(u,v)

m = int(input())
for i in range(m):
    u,v = map(int,input().split())
    root_u = Root(u-1)
    root_v = Root(v-1)

    if(root_u==root_v):
        Size[root_u] = 0

Max  = -float('inf')
for i in range(n):
   Max = max(Max,Size[Root(i)])
print(Max)

```


221_D. Little Elephant and Array

The Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.

Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1 ≤ lj ≤ rj ≤ n). For each query lj, rj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj, alj + 1, ..., arj.

Help the Little Elephant to count the answers to all queries.

Input

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1 ≤ lj ≤ rj ≤ n).

Output

In m lines print m integers — the answers to the queries. The j-th line should contain the answer to the j-th query.

Examples

Input

7 2
3 1 2 2 3 3 7
1 7
3 4

Output

3
1

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

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")
#######################################
class query():
    global z
    def __init__(self,l,r,i):
        self.lb=(l-1)//z
        self.l=l
        self.r=r
        self.ind=i
    def __lt__(a,b):
        return (a.lb<b.lb or (a.lb==b.lb and a.r<b.r))
n,m=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n):
    if a[i]>n:
        a[i]=-1
l1=[]
z=int(n**0.5)
for i in range(m):
    x,y=map(int,input().split())
    l1.append(query(x,y,i))
l1.sort()
d=[0]*(n+2)
l=1
r=0
ans=0
fans=[0]*m
for i in l1:
    while r<i.r:
        r+=1
        if d[a[r-1]]==a[r-1]:
            ans-=1
        d[a[r-1]]+=1
        if d[a[r-1]]==a[r-1]:
            ans+=1
    while l>i.l:
        l-=1
        if d[a[l-1]]==a[l-1]:
            ans-=1
        d[a[l-1]]+=1
        if d[a[l-1]]==a[l-1]:
            ans+=1
    while l<i.l:
        if d[a[l-1]]==a[l-1]:
            ans-=1
        d[a[l-1]]-=1
        if d[a[l-1]]==a[l-1]:
            ans+=1
        l+=1
    while r>i.r:
        if d[a[r-1]]==a[r-1]:
            ans-=1
        d[a[r-1]]-=1
        if d[a[r-1]]==a[r-1]:
            ans+=1
        r-=1
    fans[i.ind]=ans
for i in fans:
    print(i)

```


245_E. Mishap in Club

Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.

On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.

Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.

Input

The only line of the input contains a sequence of characters "+" and "-", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.

Output

Print the sought minimum number of people

Examples

Input

+-+-+

Output

1

Input

---

Output

3

```python
#Problem Set N: Collaborated with no one
n = input()

in_visit = 0
out_visit = 0

for i in range(len(n)):
    if n[i] == '+':
        in_visit += 1

        if out_visit:
            out_visit -= 1

    elif n[i] == '-':
        out_visit += 1

        if in_visit:
            in_visit -= 1

print(in_visit + out_visit)

```


270_C. Magical Boxes

Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes.

From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a magical box u, if side length of v is strictly less than the side length of u. In particular, Emuskald can put 4 boxes of side length 2k - 1 into one box of side length 2k, or as in the following figure:

<image>

Emuskald is about to go on tour performing around the world, and needs to pack his magical boxes for the trip. He has decided that the best way to pack them would be inside another magical box, but magical boxes are quite expensive to make. Help him find the smallest magical box that can fit all his boxes.

Input

The first line of input contains an integer n (1 ≤ n ≤ 105), the number of different sizes of boxes Emuskald has. Each of following n lines contains two integers ki and ai (0 ≤ ki ≤ 109, 1 ≤ ai ≤ 109), which means that Emuskald has ai boxes with side length 2ki. It is guaranteed that all of ki are distinct.

Output

Output a single integer p, such that the smallest magical box that can contain all of Emuskald’s boxes has side length 2p.

Examples

Input

2
0 3
1 5

Output

3

Input

1
0 4

Output

1

Input

2
1 10
2 2

Output

3

Note

Picture explanation. If we have 3 boxes with side length 2 and 5 boxes with side length 1, then we can put all these boxes inside a box with side length 4, for example, as shown in the picture.

In the second test case, we can put all four small boxes into a box with side length 2.

```python
from math import*
n = int(input())
v=0
for i in range(n):
    a = [int(x)for x in input().split(' ')]
    k = ceil(fabs(log(a[1],4)))
    if k==0: k=1
    if k+a[0]>v:
        v = k+a[0]
print(v)
```


317_C. Balance

A system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals e. Volume of each vessel equals v liters. Of course, the amount of the water in any vessel cannot exceed v liters in the process of transfusions.

Given the initial amounts ai of water in the vessels and the desired amounts bi find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2·n2.

Input

First line of the input contains integers n, v, e (1 ≤ n ≤ 300, 1 ≤ v ≤ 109, 0 ≤ e ≤ 50000).

Next two lines contain n integers each: initial ai and the desired amounts bi of water in corresponding vessels (0 ≤ ai, bi ≤ v).

Next e lines describe one tube each in the format x y (1 ≤ x, y ≤ n, x ≠ y) for a tube between vessels number x and y. There might be multiple tubes between two vessels. You may assume that vessels are numbered from 1 to n in some way.

Output

Print "NO" (without quotes), if such sequence of transfusions does not exist.

Otherwise print any suitable sequence in the following format. On the first line print the total number of transfusions k (k should not exceed 2·n2). In the following k lines print transfusions in the format x y d (transfusion of d liters from the vessel number x to the vessel number y, x and y must be distinct). For all transfusions d must be a non-negative integer.

Examples

Input

2 10 1
1 9
5 5
1 2

Output

1
2 1 4

Input

2 10 0
5 2
4 2

Output

NO

Input

2 10 0
4 2
4 2

Output

0

```python
read = lambda: map(int, input().split())
n, v, e = read()
adj = [[] for _ in range(n + 1)]
As = [0] + list(read())
Bs = [0] + list(read())
ans = []

for _ in range(e):
    a, b = map(int, input().split())
    adj[a].append(b)
    adj[b].append(a)

def flow(a, b, d):
    As[a] -= d
    As[b] += d
    ans.append((a, b, d));

def augment(path, e, d):
    if e:
        dd = min(d, As[path[e - 1]], v - As[path[e]])
        flow(path[e - 1], path[e], dd)
        augment(path, e - 1, d)
        if d > dd:
            flow(path[e - 1], path[e], d - dd);

def adjust(s):
    pre = [0] * (n + 1)
    pre[s] = -1
    stk = [s]
    e = 0
    while len(stk):
        p = stk[-1]
        del stk[-1]
        if As[p] < Bs[p]:
            e = p
            break
        for to in adj[p]:
            if not pre[to]:
                pre[to] = p
                stk.append(to)

    if not e:
        raise Exception
    path = []
    while e > 0:
        path.insert(0, e)
        e = pre[e]
    augment(path, len(path) - 1, min(Bs[path[-1]] - As[path[-1]], As[s] - Bs[s]))

try:
    while True:
        check = False
        for i in range(1, n + 1):
            if As[i] > Bs[i]:
                adjust(i)
                check = True
        if not check:
            break
    for i in range(1, n + 1):
        if As[i] != Bs[i]:
            raise Exception
    print(len(ans))
    for tp in ans:
        print(*tp)
except Exception:
    print("NO")

```


341_C. Iahub and Permutations

Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.

The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n). She replaces some of permutation elements with -1 value as a revenge.

When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).

Input

The first line contains integer n (2 ≤ n ≤ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1.

It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.

Output

Output a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).

Examples

Input

5
-1 -1 4 3 -1

Output

2

Note

For the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.

```python
#lahub and Permutations
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
mod = 10**9+7
def pow(n,p,mod=mod): #繰り返し二乗法(nのp乗)
    res = 1
    while p > 0:
        if p % 2 == 0:
            n = n ** 2 % mod
            p //= 2
        else:
            res = res * n % mod
            p -= 1
    return res % mod

def factrial_memo(n=10**5,mod=mod):
    fact = [1, 1]
    for i in range(2, n + 1):
        fact.append((fact[-1] * i) % mod)
    return fact

fact = factrial_memo()

def permutation(n,r): #nPr
    return fact[n]*pow(fact[n-r],mod-2)%mod
def combination(n,r): #nCr
    return permutation(n,r)*pow(fact[r],mod-2)%mod
    #return fact[n]*pow(fact[n-r],mod-2)*pow(fact[r],mod-2)
def homogeneous(n,r): #nHr
    return combination(n+r-1,r)%mod
    #return fact[n+m-1]*pow(fact[n-1],mod-2)*pow(fact[r],mod-2)

n = int(readline())
lst1 = list(map(int,readline().split()))
ct = 0
lst2 = [0]*2_001
lst3 = [0]*2_001
for i in range(n):
    if i+1 == lst1[i]:
        print(0)
        exit()
    if lst1[i] == -1:
        ct += 1
        lst3[i+1] = 1
    else:
        lst2[lst1[i]] = 1

ct2 = 0
for i in range(1,n+1):
    if lst3[i] == 1 and lst2[i] == 0:
        ct2 += 1
#lst2:その場所が埋まってないindex
#lst3:その数字が使われてるindex
#何個入れちゃいけない位置に入れるかで数え上げる
#入れちゃいけないものはct2個って、
#ct-ct2個のものはどこに入れても要件を満たす

ans = 0
for i in range(ct2+1):
    ans += pow(-1,i)*combination(ct2,i)*fact[ct-i]
    ans %= mod
print(ans)
```


388_D. Fox and Perfect Sets

Fox Ciel studies number theory.

She thinks a non-empty set S contains non-negative integers is perfect if and only if for any <image> (a can be equal to b), <image>. Where operation xor means exclusive or operation (http://en.wikipedia.org/wiki/Exclusive_or).

Please calculate the number of perfect sets consisting of integers not greater than k. The answer can be very large, so print it modulo 1000000007 (109 + 7).

Input

The first line contains an integer k (0 ≤ k ≤ 109).

Output

Print a single integer — the number of required sets modulo 1000000007 (109 + 7).

Examples

Input

1

Output

2

Input

2

Output

3

Input

3

Output

5

Input

4

Output

6

Note

In example 1, there are 2 such sets: {0} and {0, 1}. Note that {1} is not a perfect set since 1 xor 1 = 0 and {1} doesn't contain zero.

In example 4, there are 6 such sets: {0}, {0, 1}, {0, 2}, {0, 3}, {0, 4} and {0, 1, 2, 3}.

```python
from math import factorial
MOD = 10**9+7

k = int(input())
bink = list(map(int, bin(k)[2:]))
N = len(bink)

# dp[i][j][k] = first i bits, j bases,
#   k = 1 if maxor matches k, 0 else
dp = [[[0,0] for j in range(i+2)] for i in range(N+1)]
dp[0][0][1] = 1
for i in range(1, N+1):
    for j in range(i+1):
        # k = 0 -> 0
        dp[i][j][0]+= 2**j * dp[i-1][j][0] # distribute
        if j: dp[i][j][0]+= dp[i-1][j-1][0] # new base
        # k = 1 -> 0
        odd = 2**(j-1) if j else 0
        even = 2**j - odd
        if bink[i-1] == 1:
            dp[i][j][0]+= even * dp[i-1][j][1] # distribute even
        # k = 1 -> 1
        if bink[i-1] == 0:
            dp[i][j][1]+= even * dp[i-1][j][1] # distribute even
        else:
            dp[i][j][1]+= odd * dp[i-1][j][1] # distribute odd
            if j: dp[i][j][1]+= dp[i-1][j-1][1] # new base
ans = sum(map(sum, dp[-1]))
print(ans % MOD)
```


409_B. Mysterious Language

You are given a mysterious language (codenamed "Secret") available in "Custom Invocation" tab. Figure out what this language is and write a program which prints its name. Note that the program must be written in this language.

Input

This program has only one test (your program doesn't have to read anything).

Output

Output the name of the mysterious language. Note that the name is case-sensitive and might contain digits and special characters.

Examples

Note

Some scientists disagree on what should be considered as a language and what should be considered as a dialect.


436_C. Dungeons and Candies

During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.

<image>

When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A:

  1. You can transmit the whole level A. Then you need to transmit n·m bytes via the network.
  2. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other.

Your task is to find a way to transfer all the k levels and minimize the traffic.

Input

The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters.

Output

In the first line print the required minimum number of transferred bytes.

Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input.

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

Examples

Input

2 3 3 2
A.A
...
A.a
..C
X.Y
...

Output

14
1 0
2 1
3 1

Input

1 1 4 1
A
.
B
.

Output

3
1 0
2 0
4 2
3 0

Input

1 3 5 2
ABA
BBB
BBA
BAB
ABB

Output

11
1 0
3 1
2 3
4 2
5 1

```python
def put():
    return map(int, input().split())
def diff(x,y):
    ans = 0
    for i in range(n*m):
        if s[x][i]!= s[y][i]:
            ans+=1
    return ans
def find(i):
    if i==p[i]:
        return i
    p[i] = find(p[i])
    return p[i]
def union(i,j):
    if rank[i]>rank[j]:
        i,j = j,i
    elif rank[i]==rank[j]:
        rank[j]+=1
    p[i]= j
def dfs(i,p):
    if i!=0:
        print(i,p)
    for j in tree[i]:
        if j!=p:
            dfs(j,i)

n,m,k,w = put()
s = ['']*k
for i in range(k):
    for j in range(n):
        s[i]+=input()
edge = []
k+=1
rank = [0]*(k)
p = list(range(k))
cost = 0
tree = [[] for i in range(k)]

for i in range(k):
    for j in range(i+1,k):
        if i==0:
            z=n*m
        else:
            z = diff(i-1,j-1)*w
        edge.append((z,i,j))

edge.sort()
for z,i,j in edge:
    u = find(i)
    v = find(j)
    if u!=v:
        union(u,v)
        cost+= z
        tree[i].append(j)
        tree[j].append(i)

print(cost)
dfs(0,-1)

```


459_D. Pashmak and Parmida's problem

Parmida is a clever girl and she wants to participate in Olympiads this year. Of course she wants her partner to be clever too (although he's not)! Parmida has prepared the following test problem for Pashmak.

There is a sequence a that consists of n integers a1, a2, ..., an. Let's denote f(l, r, x) the number of indices k such that: l ≤ k ≤ r and ak = x. His task is to calculate the number of pairs of indicies i, j (1 ≤ i < j ≤ n) such that f(1, i, ai) > f(j, n, aj).

Help Pashmak with the test.

Input

The first line of the input contains an integer n (1 ≤ n ≤ 106). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Output

Print a single integer — the answer to the problem.

Examples

Input

7
1 2 1 1 2 2 1

Output

8

Input

3
1 1 1

Output

1

Input

5
1 2 3 4 5

Output

0

```python
# 459D
import sys
from collections import Counter

class BIT():
    def __init__(self, n):
        self.n = n
        self.tree = [0] * n

    def _F(self, i):
        return i & (i + 1)

    def _getSum(self, r):
        '''
        sum on interval [0, r]
        '''
        result = 0
        while r >= 0:
            result += self.tree[r]
            r = self._F(r) - 1
        return result

    def getSum(self, l, r):
        '''
        sum on interval [l, r]
        '''
        return self._getSum(r) - self._getSum(l - 1)

    def _H(self, i):
        return i | (i + 1)

    def add(self, i, value=1):
        while i < self.n:
            self.tree[i] += value
            i = self._H(i)

# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__

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

# inf.close()

freq = BIT(n+1)
f_left = [0] * n
f_right = [0] * n
ctr = Counter()
for i, val in enumerate(a):
    ctr[val] += 1
    f_left[i] = ctr[val]
for i in range(n):
    val = a[i]
    f_right[i] = ctr[val] - f_left[i] + 1
for f_r in f_right:
    freq.add(f_r, 1)
ans = 0
for i, f_l in enumerate(f_left):
    f_r = f_right[i]
    freq.add(f_r, -1)
    ans += freq.getSum(1, f_l-1)
print(ans)

```


480_C. Riding in a Lift

Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.

Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.

Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).

Input

The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).

Output

Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).

Examples

Input

5 2 4 1

Output

2

Input

5 2 4 2

Output

2

Input

5 3 4 1

Output

0

Note

Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.

Notes to the samples:

  1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
  2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
  3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.

```python
def solve(n, st, k):
    MOD = int(1e9 + 7)
    dp = [0] * (n + 1)
    prefix_sum = [0] * (n + 1)
    dp[st] = 1
    for times in range(k):
        prefix_sum[0] = 0
        for i in range(1, n + 1):
            prefix_sum[i] = prefix_sum[i - 1] + dp[i]
            if prefix_sum[i] >= MOD: prefix_sum[i] -= MOD
        for i in range(1, n + 1):
            dp[i] = prefix_sum[n] - prefix_sum[i] + prefix_sum[i - 1] - prefix_sum[i >> 1]
            while dp[i] < 0: dp[i] += MOD
            while dp[i] >= MOD: dp[i] -= MOD
    return sum(dp) % MOD

def main():
    n, a, b, k = [int(i) for i in input().split()]
    if a > b:
        print(solve(n - b, a - b, k))
    else:
        print(solve(b - 1, b - a, k))

main()

```


529_B. Group Photo 2 (online mirror version)

Many years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.

Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a wi pixels wide and a hi pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a hi pixels wide and a wi pixels high rectangle.

The total photo will have size W × H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..)

Help them to achieve this goal.

Input

The first line contains integer n (1 ≤ n ≤ 1000) — the number of friends.

The next n lines have two integers wi, hi (1 ≤ wi, hi ≤ 1000) each, representing the size of the rectangle, corresponding to the i-th friend.

Output

Print a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground.

Examples

Input

3
10 1
20 2
30 3

Output

180

Input

3
3 1
2 2
4 3

Output

21

Input

1
5 10

Output

50

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

def check(max_h):
    k = n // 2
    b = []
    for w, h in a:
        if h > max_h:
            if k <= 0 or w > max_h:
                return 1 << 60
            b.append((h, w))
            k -= 1
        else:
            b.append((w, h))
    b.sort(key=lambda t: t[1] - t[0])
    r = 0
    for w, h in b:
        if k > 0 and w <= max_h and h < w:
            r += h
            k -= 1
        else:
            r += w
    return r * max_h

print(min(check(h) for h in range(1, 1001)))

```


554_D. Kyoya and Permutation

Let's define the permutation of length n as an array p = [p1, p2, ..., pn] consisting of n distinct integers from range from 1 to n. We say that this permutation maps value 1 into the value p1, value 2 into the value p2 and so on.

Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a sequence of numbers such that each element of this sequence is being mapped into the next element of this sequence (and the last element of the cycle is being mapped into the first element of the cycle). The cyclic representation is a representation of p as a collection of cycles forming p. For example, permutation p = [4, 1, 6, 2, 5, 3] has a cyclic representation that looks like (142)(36)(5) because 1 is replaced by 4, 4 is replaced by 2, 2 is replaced by 1, 3 and 6 are swapped, and 5 remains in place.

Permutation may have several cyclic representations, so Kyoya defines the standard cyclic representation of a permutation as follows. First, reorder the elements within each cycle so the largest element is first. Then, reorder all of the cycles so they are sorted by their first element. For our example above, the standard cyclic representation of [4, 1, 6, 2, 5, 3] is (421)(5)(63).

Now, Kyoya notices that if we drop the parenthesis in the standard cyclic representation, we get another permutation! For instance, [4, 1, 6, 2, 5, 3] will become [4, 2, 1, 5, 6, 3].

Kyoya notices that some permutations don't change after applying operation described above at all. He wrote all permutations of length n that do not change in a list in lexicographic order. Unfortunately, his friend Tamaki Suoh lost this list. Kyoya wishes to reproduce the list and he needs your help. Given the integers n and k, print the permutation that was k-th on Kyoya's list.

Input

The first line will contain two integers n, k (1 ≤ n ≤ 50, 1 ≤ k ≤ min{1018, l} where l is the length of the Kyoya's list).

Output

Print n space-separated integers, representing the permutation that is the answer for the question.

Examples

Input

4 3

Output

1 3 2 4

Input

10 1

Output

1 2 3 4 5 6 7 8 9 10

Note

The standard cycle representation is (1)(32)(4), which after removing parenthesis gives us the original permutation. The first permutation on the list would be [1, 2, 3, 4], while the second permutation would be [1, 2, 4, 3].

```python
def F(n):
    a,b = 1,0
    for i in range(n):
        a,b = b,a+b
    return b

def ans(n,k):
    if n == 0:
        return []
    elif n == 1:
        return [1]
    elif k > F(n):
        return [2,1] + [i+2 for i in ans(n-2,k-F(n))]
    else:
        return [1] + [i+1 for i in ans(n-1,k)]

n,k = map(int,input().split())
print(' '.join([str(i) for i in ans(n,k)]))

```


580_C. Kefa and Park

Kefa decided to celebrate his first big salary by going to the restaurant.

He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.

The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.

Your task is to help Kefa count the number of restaurants where he can go.

Input

The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.

The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).

Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.

It is guaranteed that the given set of edges specifies a tree.

Output

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.

Examples

Input

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

Output

2

Input

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

Output

2

Note

Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.

Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.

Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.

```python
M=lambda:map(int,input().split())
n,m=M()
*c,=M()
t=[[]for i in range(n)]
v=[0]*n
for i in range(n-1):
    x,y=M()
    t[x-1].append(y-1)
    t[y-1].append(x-1)
a=i=0
q=[(0,0)]
while i<len(q):
    x,N=q[i]
    v[x]=1
    if c[x]+N<=m:
        L=1
        for y in t[x]:
            if not v[y]:
                L=0
                q.append((y,c[x]*(c[x]+N)))
        if L:
            a+=1
    i+=1
print(a)

```


602_B. Approximating a Constant Range

When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?

You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.

A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.

Find the length of the longest almost constant range.

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Output

Print a single number — the maximum length of an almost constant range of the given sequence.

Examples

Input

5
1 2 3 3 2

Output

4

Input

11
5 4 5 5 6 7 8 8 8 7 6

Output

5

Note

In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.

In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].

```python
n = int(input())
arr = list(map(int,input().split()))
d = {}
mx = 0
for c in arr:
    nd = {}
    nd[c-0.5] = d.get(c-0.5,0)+1
    nd[c+0.5] = d.get(c+0.5,0)+1
    mx = max(mx,nd[c-0.5],nd[c+0.5])
    d = nd
print(mx)
```


673_B. Problems for Round

There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules:

  * Problemset of each division should be non-empty.
  * Each problem should be used in exactly one division (yes, it is unusual requirement).
  * Each problem used in division 1 should be harder than any problem used in division 2.
  * If two problems are similar, they should be used in different divisions.

Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.

Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.

Input

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000) — the number of problems prepared for the round and the number of pairs of similar problems, respectively.

Each of the following m lines contains a pair of similar problems ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). It's guaranteed, that no pair of problems meets twice in the input.

Output

Print one integer — the number of ways to split problems in two divisions.

Examples

Input

5 2
1 4
5 2

Output

2

Input

3 3
1 2
2 3
1 3

Output

0

Input

3 2
3 1
3 2

Output

1

Note

In the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.

In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.

Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together.

```python
n, m = map(int, input().split())
s1 = set()
s2 = set()
for _ in range(m):
    a, b = map(int, input().split())
    a, b = min(a, b), max(a, b)
    if a in s2 or b in s1:
        print(0)
        exit(0)
    s1.add(a)
    s2.add(b)
if not s2:
    s2.add(n)
    s1.add(1)
print(max(0, min(s2) - max(s1)))
```


719_C. Efim and Strange Grade

Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer).

There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.

In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.

For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

Input

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively.

The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Output

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

Examples

Input

6 1
10.245

Output

10.25

Input

6 2
10.245

Output

10.3

Input

3 100
9.2

Output

9.2

Note

In the first two samples Efim initially has grade 10.245.

During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.

In the third sample the optimal strategy is to not perform any rounding at all.

```python
n, t = map(int, input().split())
tmp = input()
s = []
for i in range(n):
    s.append(tmp[i])
ind = n
perenos = 0
for i in range(n):
    if (s[i] == '.'):
        nach = i + 1
for i in range(nach, n):
    if (int(s[i]) > 4):
        ind = i
        break
if (ind == n):
    print(*s, sep="")
    exit()
while (t > 0 and s[ind] != '.'):
    if (int(s[ind]) > 3):
        ind -= 1
        perenos = 1
        t -= 1
        if (s[ind] == '9'):
            t += 1
    else:
        s[ind] = str(int(s[ind]) + 1)
        perenos = 0
        break
if s[ind] == '.':
    ind -= 1
    while (s[ind] == '9'):
        s[ind] = '0'
        ind -= 1
    if (ind < 0 and perenos != 0):
        print(1, end="")
        viv = 0
        while (s[viv] != '.'):
            print(s[viv], end="")
            viv += 1
    else:
        s[ind] = str(int(s[ind]) + perenos)
        viv = 0
        while (s[viv] != '.'):
            print(s[viv], end="")
            viv += 1
else:
    while (s[ind] == '9' or s[ind] == '.'):
        if (s[ind] == '.'):
            ind -= 1
            continue
        s[ind] = '0'
        ind -= 1
    s[ind] = str(int(s[ind]) + perenos)
    for i in range(ind + 1):
        print(s[i], end="")

```


740_A. Alyona and copybooks

Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of three copybooks for c rubles. Alyona already has n copybooks.

What is the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.

Input

The only line contains 4 integers n, a, b, c (1 ≤ n, a, b, c ≤ 109).

Output

Print the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4.

Examples

Input

1 1 3 4

Output

3

Input

6 2 1 1

Output

1

Input

4 4 4 4

Output

0

Input

999999999 1000000000 1000000000 1000000000

Output

1000000000

Note

In the first example Alyona can buy 3 packs of 1 copybook for 3a = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally.

In the second example Alyuna can buy a pack of 2 copybooks for b = 1 ruble. She will have 8 copybooks in total.

In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.

In the fourth example Alyona should buy one pack of one copybook.

```python

n, a, b, c = map(int, input().split())
h=n%4
if h==0:
	d=0
else:
	if h==1:
		d=min(a*3,a+b,c)
	if h==2:
		d=min(a*2,b,c*2)
	if h==3:
		d=min(a,b+c,c*3)
print(d)
```


787_B. Not Afraid

Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them.

There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.

Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility).

<image>

Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world).

Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.

Input

The first line of input contains two integers n and m (1 ≤ n, m ≤ 104) — number of universes and number of groups respectively.

The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k > 0) followed by k integers vi, 1, vi, 2, ..., vi, k. If vi, j is negative, it means that Rick from universe number  - vi, j has joined this group and otherwise it means that Morty from universe number vi, j has joined it.

Sum of k for all groups does not exceed 104.

Output

In a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.

Examples

Input

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

Output

YES

Input

5 2
5 3 -2 1 -1 5
3 -5 2 5

Output

NO

Input

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

Output

YES

Note

In the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event.

```python
def test(l):
    l1=[]
    l2=[]
    for i in range(len(l)):
        if l[i]<0 and l[i] not in l2:
            l2.append(l[i])
        elif l[i]>0 and l[i] not in l1:
            l1.append(l[i])
    if len(l1)==0 or len(l2)==0:
        return False
    for x in l1:
        if (x*(-1)) in l2:
            return True
    for x in l2:
        if (x*(-1)) in l1:
            return True
    return False
n,m=input().strip().split(' ')
n,m=(int(n),int(m))
for t_0 in range(m):
    list1=list(map(int,input().strip().split(' ')))
    if test(list1[1:])==False:
        print("YES")
        exit()
print("NO")
```


924_B. Three-level Laser

An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme.

Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:

  1. initially the atom is in the state i,
  2. we spend Ek - Ei energy to put the atom in the state k,
  3. the atom emits a photon with useful energy Ek - Ej and changes its state to the state j,
  4. the atom spontaneously changes its state to the state i, losing energy Ej - Ei,
  5. the process repeats from step 1.

Let's define the energy conversion efficiency as <image>, i. e. the ration between the useful energy of the photon and spent energy.

Due to some limitations, Arkady can only choose such three states that Ek - Ei ≤ U.

Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.

Input

The first line contains two integers n and U (3 ≤ n ≤ 105, 1 ≤ U ≤ 109) — the number of states and the maximum possible difference between Ek and Ei.

The second line contains a sequence of integers E1, E2, ..., En (1 ≤ E1 < E2... < En ≤ 109). It is guaranteed that all Ei are given in increasing order.

Output

If it is not possible to choose three states that satisfy all constraints, print -1.

Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9.

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

Examples

Input

4 4
1 3 5 7

Output

0.5

Input

10 8
10 13 15 16 17 19 20 22 24 25

Output

0.875

Input

3 1
2 5 10

Output

-1

Note

In the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to <image>.

In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to <image>.

```python
import heapq
from bisect import bisect_left, bisect_right
from collections import Counter
from collections import OrderedDict
from collections import deque
from itertools import accumulate, product

import math

R = lambda: map(int, input().split())

n, u= R()
arr = list(R())
res = -1
for l in range(n):
    r = bisect_right(arr, arr[l] + u) - 1
    if r - l > 1:
        res = max(res, (arr[r] - arr[l + 1]) / (arr[r] - arr[l]))
print(res)
```


952_D. I'm Feeling Lucky!

<image>

You have one chip and one chance to play roulette. Are you feeling lucky?

Output

Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).


99_A. Help Far Away Kingdom

In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.

Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this:

  * If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part.
  * If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part.
  * If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position.

Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?

Input

The first line contains a single number to round up — the integer part (a non-empty set of decimal digits that do not start with 0 — with the exception of a case when the set consists of a single digit — in this case 0 can go first), then follows character «.» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.

Output

If the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).

Examples

Input

0.0

Output

0

Input

1.49

Output

1

Input

1.50

Output

2

Input

2.71828182845904523536

Output

3

Input

3.14159265358979323846

Output

3

Input

12345678901234567890.1

Output

12345678901234567890

Input

123456789123456789.999

Output

GOTO Vasilisa.

```python
import sys
import math
import itertools
import collections

def getdict(n):
    d = {}
    if type(n) is list or type(n) is str:
        for i in n:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
    else:
        for i in range(n):
            t = ii()
            if t in d:
                d[t] += 1
            else:
                d[t] = 1
    return d
def divs(n, start=1):
    r = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if (n % i == 0):
            if (n / i == i):
                r.append(i)
            else:
                r.extend([i, n // i])
    return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a*b) // math.gcd(a, b)
def wr(arr): return ' '.join(map(str, arr))
def revn(n): return int(str(n)[::-1])
def prime(n):
    if n == 2: return True
    if n % 2 == 0 or n <= 1: return False
    sqr = int(math.sqrt(n)) + 1
    for d in range(3, sqr, 2):
        if n % d == 0: return False
    return True
def convn(number, base=3):
    newnumber = ''
    while number > 0:
        newnumber = str(number % base) + newnumber
        number //= base
    return newnumber

n = input()
pointpos = n.find('.')
if n[pointpos - 1] == '9':
    print('GOTO Vasilisa.')
elif n[pointpos + 1] > '4':
    print(n[:pointpos - 1] + chr(ord(n[pointpos - 1]) + 1))
else:
    print(n[:pointpos])

```


p02538 ACL Beginner Contest - Replace Digits

You have a string S of length N. Initially, all characters in S are `1`s.

You will perform queries Q times. In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit). Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.

After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.

Constraints

* 1 \leq N, Q \leq 200,000
* 1 \leq L_i \leq R_i \leq N
* 1 \leq D_i \leq 9
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q

Output

Print Q lines. In the i-th line print the value of S after the i-th query, modulo 998,244,353.

Examples

Input

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

Output

11222211
77772211
77333333
72333333
72311333

Input

200000 1
123 456 7

Output

641437905

```python
MOD = 998244353
class LazySegmentTree:  # from https://atcoder.jp/contests/practice2/submissions/16598122
    __slots__ = ["n", "data", "lazy", "me", "oe", "fmm", "fmo", "foo"]

    def __init__(self, monoid_data, monoid_identity, operator_identity, func_monoid_monoid, func_monoid_operator,
                func_operator_operator):
        self.me = monoid_identity
        self.oe = operator_identity
        self.fmm = func_monoid_monoid
        self.fmo = func_monoid_operator
        self.foo = func_operator_operator

        self.n = len(monoid_data)
        self.data = monoid_data*2
        for i in range(self.n-1, 0, -1):
            self.data[i] = self.fmm(self.data[2*i], self.data[2*i+1])
        self.lazy = [self.oe]*(self.n*2)

    def replace(self, index, value):
        index += self.n

        # propagation
        for shift in range(index.bit_length()-1, 0, -1):
            i = index>>shift
            self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i])
            self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i])
            self.data[i] = self.fmo(self.data[i], self.lazy[i])
            self.lazy[i] = self.oe

        # update
        self.data[index] = value
        self.lazy[index] = self.oe

        # recalculation
        i = index
        while i > 1:
            i //= 2
            self.data[i] = self.fmm(self.fmo(self.data[2*i], self.lazy[2*i]),
                                    self.fmo(self.data[2*i+1], self.lazy[2*i+1]))
            self.lazy[i] = self.oe

    def effect(self, l, r, operator):
        l += self.n
        r += self.n

        # preparing indices
        indices = []
        l0 = (l//(l&-l)) >> 1
        r0 = (r//(r&-r)-1) >> 1
        while r0 > l0:
            indices.append(r0)
            r0 >>= 1
        while l0 > r0:
            indices.append(l0)
            l0 >>= 1
        while l0 and l0 != r0:
            indices.append(r0)
            r0 >>= 1
            if l0 == r0:
                break
            indices.append(l0)
            l0 >>= 1
        while r0:
            indices.append(r0)
            r0 >>= 1

        # propagation
        for i in reversed(indices):
            self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i])
            self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i])
            self.data[i] = self.fmo(self.data[i], self.lazy[i])
            self.lazy[i] = self.oe

        # effect
        while l < r:
            if l&1:
                self.lazy[l] = self.foo(self.lazy[l], operator)
                l += 1
            if r&1:
                r -= 1
                self.lazy[r] = self.foo(self.lazy[r], operator)
            l >>= 1
            r >>= 1

        # recalculation
        for i in indices:
            self.data[i] = self.fmm(self.fmo(self.data[2*i], self.lazy[2*i]),
                                    self.fmo(self.data[2*i+1], self.lazy[2*i+1]))
            self.lazy[i] = self.oe

    def folded(self, l, r):
        l += self.n
        r += self.n

        # preparing indices
        indices = []
        l0 = (l//(l&-l))//2
        r0 = (r//(r&-r)-1)//2
        while r0 > l0:
            indices.append(r0)
            r0 >>= 1
        while l0 > r0:
            indices.append(l0)
            l0 >>= 1
        while l0 and l0 != r0:
            indices.append(r0)
            r0 >>= 1
            if l0 == r0:
                break
            indices.append(l0)
            l0 >>= 1
        while r0:
            indices.append(r0)
            r0 >>= 1

        # propagation
        for i in reversed(indices):
            self.lazy[2*i] = self.foo(self.lazy[2*i], self.lazy[i])
            self.lazy[2*i+1] = self.foo(self.lazy[2*i+1], self.lazy[i])
            self.data[i] = self.fmo(self.data[i], self.lazy[i])
            self.lazy[i] = self.oe

        # fold
        left_folded = self.me
        right_folded = self.me
        while l < r:
            if l&1:
                left_folded = self.fmm(left_folded, self.fmo(self.data[l], self.lazy[l]))
                l += 1
            if r&1:
                r -= 1
                right_folded = self.fmm(self.fmo(self.data[r], self.lazy[r]), right_folded)
            l >>= 1
            r >>= 1
        return self.fmm(left_folded, right_folded)
class ModInt:

    def __init__(self, x):
        self.x = x.x if isinstance(x, ModInt) else x % MOD

    __str__ = lambda self:str(self.x)
    __repr__ = __str__
    __int__ = lambda self: self.x
    __index__ = __int__

    __add__ = lambda self, other: ModInt(self.x + ModInt(other).x)
    __sub__ = lambda self, other: ModInt(self.x - ModInt(other).x)
    __mul__ = lambda self, other: ModInt(self.x * ModInt(other).x)
    __pow__ = lambda self, other: ModInt(pow(self.x, ModInt(other).x, MOD))
    __truediv__ = lambda self, other: ModInt(self.x * pow(ModInt(other).x, MOD - 2, MOD))
    __floordiv__ = lambda self, other: ModInt(self.x // ModInt(other).x)
    __radd__ = lambda self, other: ModInt(other + self.x)
    __rsub__ = lambda self, other: ModInt(other - self.x)
    __rpow__ = lambda self, other: ModInt(pow(other, self.x, MOD))
    __rmul__ = lambda self, other: ModInt(other * self.x)
    __rtruediv__ = lambda self, other: ModInt(other * pow(self.x, MOD - 2, MOD))
    __rfloordiv__ = lambda self, other: ModInt(other // self.x)

    __lt__ = lambda self, other: self.x < ModInt(other).x
    __gt__ = lambda self, other: self.x > ModInt(other).x
    __le__ = lambda self, other: self.x <= ModInt(other).x
    __ge__ = lambda self, other: self.x >= ModInt(other).x
    __eq__ = lambda self, other: self.x == ModInt(other).x
    __ne__ = lambda self, other: self.x != ModInt(other).x
def main():
    import sys
    sys.setrecursionlimit(311111)
    # import numpy as np
    ikimasu = sys.stdin.buffer.readline
    ini = lambda: int(ins())
    ina = lambda: list(map(int, ikimasu().split()))
    ins = lambda: ikimasu().strip()
    n,q  = ina()

    tmp = [(1,1) for i in range(0,n)]
    tmpx = 1
    tmpx1 = 1
    ten = []
    one = []
    for i in range(311111):
        ten.append(tmpx)
        one.append(tmpx1)
        tmpx1*=10
        tmpx1+=1
        tmpx*=10
        tmpx1%=MOD
        tmpx%=MOD
    # print(ten)
    def op(x1,x2):
        val1,size1 = x1
        val2,size2 = x2
        size = size1+size2
        val = (val1*ten[size2])+val2
        return val%MOD,size
    e = (0,0)
    def maptmp(s,f):
        if(f == -1):
            return s
        else:
            return f*one[s[1]-1]%MOD,s[1]
    def comp(g,f):
        return f if f!=-1 else g

    ident = -1
    tmptree = LazySegmentTree(tmp,e,ident,op,maptmp,comp)

    for _ in range(q):
        l,r,x = ina()
        tmptree.effect(l-1,r,x)
        print(tmptree.folded(0,n)[0])

if __name__ == "__main__":
    main()

```


p02669 AtCoder Grand Contest 044 - Pay to Win

You start with the number 0 and you want to reach the number N.

You can change the number, paying a certain amount of coins, with the following operations:

* Multiply the number by 2, paying A coins.
* Multiply the number by 3, paying B coins.
* Multiply the number by 5, paying C coins.
* Increase or decrease the number by 1, paying D coins.

You can perform these operations in arbitrary order and an arbitrary number of times.

What is the minimum number of coins you need to reach N?

You have to solve T testcases.

Constraints

* 1 \le T \le 10
* 1 \le N \le 10^{18}
* 1 \le A, B, C, D \le 10^9
* All numbers N, A, B, C, D are integers.

Input

The input is given from Standard Input. The first line of the input is

T

Then, T lines follow describing the T testcases. Each of the T lines has the format

N A B C D

Output

For each testcase, print the answer on Standard Output followed by a newline.

Example

Input

5
11 1 2 4 8
11 1 2 2 8
32 10 8 5 4
29384293847243 454353412 332423423 934923490 1
900000000000000000 332423423 454353412 934923490 987654321

Output

20
19
26
3821859835
23441258666

```python
from heapq import heapify, heappop, heappush
from collections import defaultdict
Inf = 10**28
inpl = lambda: list(map(int,input().split()))
T = int(input())
for _ in range(T):
    N, A, B, C, D = inpl()
    visited = defaultdict(lambda: Inf)
    ans = Inf
    pool = [(0,N)] # coin, number
    while pool:
        c, n = heappop(pool)
        if c >= ans:
            break
        elif c > visited[n]:
            continue
        q = c + D*n
        if q < ans:
            ans = q

        for mag, cost in [(2,A), (3,B), (5,C)]:
            m = (n+mag//2)//mag
            q = c + abs(n - mag*m)*D + cost
            if q < ans and q < visited[m]:
                visited[m] = q
                heappush(pool, (q, m))

    print(ans)

```


p02798 Keyence Programming Contest 2020 - Swap and Flip

We have N cards numbered 1, 2, ..., N. Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side. Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up.

Determine whether it is possible to have a non-decreasing sequence facing up from left to right (that is, for each i (1 \leq i \leq N - 1), the integer facing up on the (i+1)-th card from the left is not less than the integer facing up on the i-th card from the left) by repeating the operation below. If the answer is yes, find the minimum number of operations required to achieve it.

* Choose an integer i (1 \leq i \leq N - 1). Swap the i-th and (i+1)-th cards from the left, then flip these two cards.

Constraints

* 1 \leq N \leq 18
* 1 \leq A_i, B_i \leq 50 (1 \leq i \leq N)
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If it is impossible to have a non-decreasing sequence, print `-1`. If it is possible, print the minimum number of operations required to achieve it.

Examples

Input

3
3 4 3
3 2 3

Output

1

Input

2
2 1
1 2

Output

-1

Input

4
1 2 3 4
5 6 7 8

Output

0

Input

5
28 15 22 43 31
20 22 43 33 32

Output

-1

Input

5
4 46 6 38 43
33 15 18 27 37

Output

3

```python
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
ans = 10**10
for bit in range(1<<n):
  l = a[:]
  rev = [0]*n
  for i in range(n):
    if bit & 1<<i:
      rev[i] = 1
      l[i] = b[i]
  if sum(rev) % 2:
    continue
  odd = list()
  even = list()
  for i in range(n):
    if rev[i]^(i&1):
      even.append((l[i],i))
    else:
      odd.append((l[i],i))
  if len(even) != n//2:
    continue
  odd.sort()
  even.sort()
  l = list()
  for x,y in zip(odd,even):
    l.append(x)
    l.append(y)
  if n&1: l.append(odd[-1])
  fl = 0
  for x,y in zip(l,l[1:]):
    if x[0] > y[0]:
      fl = 1
      break
  if fl: continue
  f = [x[1] for x in l]
  # print('ok', bit, even, odd)
  cnt = 0
  g = [0]*n
  for x in f:
    cnt += sum(g[x:])
    g[x] = 1
  if ans > cnt:
    ans = cnt
if ans > 10**9:
  ans = -1
print(ans)
```


p02934 AtCoder Beginner Contest 138 - Resistors in Parallel

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

* 1 \leq N \leq 100
* 1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

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

Examples

Input

2
10 30

Output

7.5

Input

3
200 200 200

Output

66.66666666666667

Input

1
1000

Output

1000

```python
n,a=open(0)
print(1/sum(1/int(i)for i in a.split()))
```