1216_F. Wi-Fi

You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n.

You have to connect all n rooms to the Internet.

You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins.

Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers.

Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have.

Input

The first line of the input contains two integers n and k (1 ≤ n, k ≤ 2 ⋅ 10^5) — the number of rooms and the range of each router.

The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room.

Output

Print one integer — the minimum total cost of connecting all n rooms to the Internet.

Examples

Input

5 2
00100

Output

3

Input

6 1
000000

Output

21

Input

4 1
0011

Output

4

Input

12 6
000010000100

Output

15

Note

In the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3.

In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21.

In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4.

In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15.

```python
mod=10**9+7
from sys import stdin, stdout
import bisect
from bisect import bisect_left as bl              #c++ lowerbound bl(array,element)
from bisect import bisect_right as br             #c++ upperbound
import itertools
import collections
import math
import heapq
from random import randint as rn
def modinv(n,p):
    return pow(n,p-2,p)
def ncr(n,r,p):                        #for using this uncomment the lines calculating fact and ifact
    t=((fact[n])*((ifact[r]*ifact[n-r])%p))%p
    return t
def ain():                           #takes array as input
    return list(map(int,sin().split()))
def sin():
    return input()
def inin():
    return int(input())
def GCD(x,y):
    while(y):
        x, y = y, x % y
    return x
"""*******************************************************"""
def main():
	n,k=map(int,input().split())
	s=sin()
	q=[]
	g=[0]
	for i in range(1,n+1):
		g.append(g[i - 1] + i)
	f=[0]*200001
	mi = 1000000000000000
	ans = g[n];
	z=0
	for i in range(1,n+1):
		if (s[i-1] == '0'):
		    continue
		f[i] = g[max(0, i - k - 1)] + i;
		while (len(q)>0 and z<len(q) and q[z] < i - 2 * k - 1):
			mi = min(mi, f[q[z]] - g[q[z] + k])
			z+=1
		if (len(q)>0 and z<len(q)):
		    f[i] = min(f[i], f[q[z]] + i)
		if (i > k):
		    f[i] = min(f[i], g[i - k - 1] + mi + i)
		while (len(q)>0 and f[-1] > f[i]):
		    q.pop()
		q.append(i)
		ans = min(ans, g[n] - g[min(n, i + k)] + f[i]);
	print(ans)
######## Python 2 and 3 footer by Pajenegod and c1729
py2 = round(0.5)
if py2:
    from future_builtins import ascii, filter, hex, map, oct, zip
    range = xrange

import os, sys
from io import IOBase, BytesIO

BUFSIZE = 8192
class FastIO(BytesIO):
    newlines = 0

    def __init__(self, file):
        self._file = file
        self._fd = file.fileno()
        self.writable = "x" in file.mode or "w" in file.mode
        self.write = super(FastIO, self).write if self.writable else None

    def _fill(self):
        s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
        self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0])
        return s

    def read(self):
        while self._fill(): pass
        return super(FastIO,self).read()

    def readline(self):
        while self.newlines == 0:
            s = self._fill(); self.newlines = s.count(b"\n") + (not s)
        self.newlines -= 1
        return super(FastIO, self).readline()

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

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        if py2:
            self.write = self.buffer.write
            self.read = self.buffer.read
            self.readline = self.buffer.readline
        else:
            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')

if __name__ == '__main__':
    main()
#threading.Thread(target=main).start()

```


123_B. Squares

You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one.

A square (x; y) is considered bad, if at least one of the two conditions is fulfilled:

  * |x + y| ≡ 0 (mod 2a),
  * |x - y| ≡ 0 (mod 2b).

Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).

Input

The only line contains integers a, b, x1, y1, x2 and y2 — the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≤ a, b ≤ 109 and |x1|,|y1|,|x2|,|y2| ≤ 109). It is guaranteed that the initial and the final square aren't bad.

Output

Print a single number — the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).

Examples

Input

2 2 1 0 0 1

Output

1

Input

2 2 10 11 0 1

Output

5

Input

2 4 3 -1 3 7

Output

2

Note

In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.


125_C. Hobbits' Party

Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.

Input

The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits.

Output

In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.

Examples

Input

4

Output

3
1 2
1 3
2 3

Input

5

Output

3
1 2
1 3
2 3

```python
n = int(input())
d = int(0.5 + (1 + 8*n)**0.5 / 2)
curr = 1
res = [[] for _ in range(d)]

for i in range(d):
    j = i + 1
    while len(res[i]) < d - 1:
        res[i].append(str(curr))
        res[j].append(str(curr))
        curr += 1
        j += 1
print(d)
for l in res:
    print(' '.join(l))
```


1281_E. Jeremy Bearimy

Welcome! Everything is fine.

You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.

You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.

Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.

The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.

As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are:

  * The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other;
  * The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other.

What are the values of G and B?

Input

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

The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≤ k ≤ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≤ a_i, b_i ≤ 2k, a_i ≠ b_i, 1 ≤ t_i ≤ 10^6). It is guaranteed that the given roads define a tree structure.

It is guaranteed that the sum of the k in a single file is at most 3 ⋅ 10^5.

Output

For each test case, output a single line containing two space-separated integers G and B.

Example

Input

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

Output

15 33
6 6

Note

For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment:

  * The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5;
  * The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6;
  * The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4.

Note that the sum of the f(i) is 5 + 6 + 4 = 15.

We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment:

  * The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6;
  * The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14;
  * The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13.

Note that the sum of the f(i) is 6 + 14 + 13 = 33.

```python
import sys

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

def solve():
	k = int(input())
	n = 2*k
	e = [[] for i in range(n)]
	p = [None]*(n)
	for i in range(n-1):
		a, b, t = map(int, input().split())
		a -= 1
		b -= 1
		e[a].append((b,t))
		e[b].append((a,t))
	q = [0]
	qi = 0
	while qi < len(q):
		x = q[qi]
		qi += 1
		px = p[x]
		for v, w in e[x]:
			if v != px:
				q.append(v)
				p[v] = x
	d1 = [False] * n
	d2 = [0] * n
	m = 0
	M = 0
	for qi in range(len(q)-1,-1,-1):
		x = q[qi]
		px = p[x]
		cnt = 1
		c1 = 1
		for v, w in e[x]:
			if v != px:
				if d1[v]:
					m += w
					cnt += 1
				dv = d2[v]
				M += w * min(dv, n - dv)
				c1 += dv
		d1[x] = cnt % 2
		d2[x] = c1
	print(m, M)

for i in range(int(input())):
	solve()

```


1301_E. Nanosoft

Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.

The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.

An Example of some correct logos:

<image>

An Example of some incorrect logos:

<image>

Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').

Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0.

Warawreh couldn't find the best option himself so he asked you for help, can you help him?

Input

The first line of input contains three integers n, m and q (1 ≤ n , m ≤ 500, 1 ≤ q ≤ 3 ⋅ 10^{5}) — the number of row, the number columns and the number of options.

For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.

For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≤ r_1 ≤ r_2 ≤ n, 1 ≤ c_1 ≤ c_2 ≤ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2).

Output

For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0.

Examples

Input

5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5

Output

16
4
4
4
0

Input

6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10

Output

36
4
16
16
16

Input

8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5

Output

64
0
16
4
16
4
36
0

Note

Picture for the first test:

<image>

The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray.

```python
def main():
    import sys
    input = sys.stdin.buffer.readline

    # max
    def STfunc(a, b):
        if a > b:
            return a
        else:
            return b

    # クエリは0-indexedで[(r1, c1), (r2, c2))
    class SparseTable():
        def __init__(self, grid):
            # A: 処理したい2D配列
            self.N = len(grid)
            self.M = len(grid[0])
            self.KN = self.N.bit_length() - 1
            self.KM = self.M.bit_length() - 1
            self.flatten = lambda n, m, kn, km: \
                (n * self.M + m) * ((self.KN + 1) * (self.KM + 1)) + (kn * (self.KM + 1) + km)
            self.table = [0] * (self.flatten(self.N - 1, self.M - 1, self.KN, self.KM) + 1)
            for i, line in enumerate(grid):
                for j, val in enumerate(line):
                    self.table[self.flatten(i, j, 0, 0)] = val
            for km in range(1, self.KM + 1):
                for i in range(self.N):
                    for j in range(self.M):
                        j2 = j + (1 << (km - 1))
                        if j2 <= self.M - 1:
                            self.table[self.flatten(i, j, 0, km)] = \
                                STfunc(self.table[self.flatten(i, j, 0, km - 1)],
                                       self.table[self.flatten(i, j2, 0, km - 1)])
            for kn in range(1, self.KN + 1):
                for km in range(self.KM + 1):
                    for i in range(self.N):
                        i2 = i + (1 << (kn - 1))
                        for j in range(self.M):
                            if i2 <= self.N - 1:
                                self.table[self.flatten(i, j, kn, km)] = \
                                    STfunc(self.table[self.flatten(i, j, kn - 1, km)],
                                           self.table[self.flatten(i2, j, kn - 1, km)])

        def query(self, r1, c1, r2, c2):
            # [(r1, c1), (r2, c2))の最小値を求める
            kr = (r2 - r1).bit_length() - 1
            kc = (c2 - c1).bit_length() - 1
            r2 -= (1 << kr)
            c2 -= (1 << kc)
            return STfunc(STfunc(self.table[self.flatten(r1, c1, kr, kc)], self.table[self.flatten(r2, c1, kr, kc)]),
                          STfunc(self.table[self.flatten(r1, c2, kr, kc)], self.table[self.flatten(r2, c2, kr, kc)]))

    H, W, Q = map(int, input().split())
    grid = []
    for _ in range(H):
        grid.append(input())
    #print(grid)

    R = [[0] * W for _ in range(H)]
    G = [[0] * W for _ in range(H)]
    Y = [[0] * W for _ in range(H)]
    B = [[0] * W for _ in range(H)]
    R_enc = ord('R')
    G_enc = ord('G')
    Y_enc = ord('Y')
    B_enc = ord('B')
    for h in range(H):
        for w in range(W):
            if grid[h][w] == R_enc:
                R[h][w] = 1
            elif grid[h][w] == G_enc:
                G[h][w] = 1
            elif grid[h][w] == Y_enc:
                Y[h][w] = 1
            else:
                B[h][w] = 1

    for h in range(1, H):
        for w in range(1, W):
            if R[h][w]:
                tmp = min(R[h-1][w-1], R[h-1][w], R[h][w-1]) + 1
                if tmp > 1:
                    R[h][w] = tmp
    for h in range(1, H):
        for w in range(W-2, -1, -1):
            if G[h][w]:
                tmp = min(G[h-1][w+1], G[h-1][w], G[h][w+1]) + 1
                if tmp > 1:
                    G[h][w] = tmp
    for h in range(H-2, -1, -1):
        for w in range(1, W):
            if Y[h][w]:
                tmp = min(Y[h+1][w-1], Y[h+1][w], Y[h][w-1]) + 1
                if tmp > 1:
                    Y[h][w] = tmp
    for h in range(H-2, -1, -1):
        for w in range(W-2, -1, -1):
            if B[h][w]:
                tmp = min(B[h+1][w+1], B[h+1][w], B[h][w+1]) + 1
                if tmp > 1:
                    B[h][w] = tmp

    M = [[0] * W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            if h < H-1 and w < W-1:
                M[h][w] = min(R[h][w], G[h][w+1], Y[h+1][w], B[h+1][w+1])

    ST = SparseTable(M)
    ans = [None] * Q
    for q in range(Q):
        r1, c1, r2, c2 = map(int, input().split())
        r1 -= 1
        c1 -= 1
        r2 -= 1
        c2 -= 1
        ok = 0
        ng = 501
        mid = 250
        while ng - ok > 1:
            R1 = r1 + mid - 1
            C1 = c1 + mid - 1
            R2 = r2 - mid + 1
            C2 = c2 - mid + 1
            if R1 >= R2 or C1 >= C2:
                ng = mid
                mid = (ok + ng)//2
                continue
            #print(ST.query(R1, C1, R2, C2), mid, [R1, C1, R2, C2])
            if ST.query(R1, C1, R2, C2) >= mid:
                ok = mid
            else:
                ng = mid
            mid = (ok+ng)//2
        #[print(M[h]) for h in range(H)]
        ans[q] = (2*ok)**2
    sys.stdout.write('\n'.join(map(str, ans)))

if __name__ == '__main__':
    main()

```


1325_E. Ehab's REAL Number Theory Problem

You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.

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

Input

The first line contains an integer n (1 ≤ n ≤ 10^5) — the length of a.

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

Output

Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".

Examples

Input

3
1 4 6

Output

1

Input

4
2 3 6 6

Output

2

Input

3
6 15 10

Output

3

Input

4
2 3 5 7

Output

-1

Note

In the first sample, you can choose a subsequence [1].

In the second sample, you can choose a subsequence [6, 6].

In the third sample, you can choose a subsequence [6, 15, 10].

In the fourth sample, there is no such subsequence.

```python
from collections import deque
import sys
input=sys.stdin.readline

def make_mf():
    res=[-1]*(mxa+5)
    ptoi=[0]*(mxa+5)
    pn=1
    for i in range(2,mxa+5):
        if res[i]==-1:
            res[i]=i
            ptoi[i]=pn
            pn+=1
            for j in range(i**2,mxa+5,i):
                if res[j]==-1:res[j]=i
    return res,ptoi,pn

def make_to():
    to=[[] for _ in range(pn)]
    ss=set()
    for a in aa:
        pp=[]
        while a>1:
            p=mf[a]
            e=0
            while p==mf[a]:
                a//=p
                e^=1
            if e:pp.append(p)
        if len(pp)==0:ext(1)
        elif len(pp)==1:pp.append(1)
        u,v=ptoi[pp[0]],ptoi[pp[1]]
        to[u].append(v)
        to[v].append(u)
        if pp[0]**2<=mxa:ss.add(u)
        if pp[1]**2<=mxa:ss.add(v)
    return to,ss

def ext(ans):
    print(ans)
    exit()

def solve():
    ans=inf
    for u in ss:
        ans=bfs(u,ans)
    if ans==inf:ans=-1
    return ans

def bfs(u,ans):
    dist=[-1]*pn
    q=deque()
    q.append((u,0,-1))
    dist[u]=0
    while q:
        u,d,pu=q.popleft()
        if d*2>=ans:break
        for v in to[u]:
            if v==pu:continue
            if dist[v]!=-1:ans=min(ans,d+dist[v]+1)
            dist[v]=d+1
            q.append((v,d+1,u))
    return ans

inf=10**9
n=int(input())
aa=list(map(int,input().split()))
mxa=max(aa)
mf,ptoi,pn=make_mf()
to,ss=make_to()
print(solve())

```


1344_D. Résumé Review

Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.)

You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your résumé has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired.

You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired:

$$$ f(b_1,…,b_n)=∑_{i=1}^n b_i(a_i-b_i^2). $$$

Here, b_i denotes the number of projects of type i you include in your résumé. Of course, you cannot include more projects than you have completed, so you require 0≤ b_i ≤ a_i for all i.

Your résumé only has enough room for k projects, and you will absolutely not be hired if your résumé has empty space, so you require ∑_{i=1}^n b_i=k.

Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints.

Input

The first line contains two integers n and k (1≤ n≤ 10^5, 1≤ k≤ ∑_{i=1}^n a_i) — the number of types of programming projects and the résumé size, respectively.

The next line contains n integers a_1,…,a_n (1≤ a_i≤ 10^9) — a_i is equal to the number of completed projects of type i.

Output

In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≤ b_i≤ a_i and ∑_{i=1}^n b_i=k. If there are multiple solutions, output any.

Note that you do not have to output the value f(b_1,…,b_n).

Examples

Input

10 32
1 2 3 4 5 5 5 5 5 5

Output

1 2 3 3 3 4 4 4 4 4

Input

5 8
4 4 8 2 1

Output

2 2 2 1 1

Note

For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint ∑_{i=1}^n b_i=k.

For the second test, the optimal answer is f=9.

```python
import os
import sys
#sys.setrecursionlimit(int(2e5))
from collections import deque
import math
readline = sys.stdin.readline
#####################################################################################

class CF(object):
    def __init__(self):
        self.eps = 1e-7
        self.n, self.k = list(map(int, readline().split()))
        self.a = list(map(int, readline().split()))
        assert(len(self.a) == self.n)

    def fd(self, i):
        return 3*i*(i+1) + 1

    def find_le(self, x, ca):
        if(self.fd(0) > x): return 0, 0
        ans = int(((12*x-3) **.5 - 3)/6 + self.eps)
        ans = int(min(ans, ca-1))
        return int(ans + 1), int(3*ans*(ans+1) + 1 == x)

    def get_num(self, x):
        st = 0
        se = 0
        for ca in self.a:
            t1,t2 = self.find_le(x+ca, ca)
            st += t1
            se += t2
        pass
        return st,se

    def find_k(self, k):
        l = int(-4e18)
        r = int(4e18)
        while(l != r):
            mid = int((l+r+1)//2)
            #print(mid)
            st, se = self.get_num(mid)
            the_max = st
            the_min = the_max - se
            # if(k>= the_min and k <= the_max):
            #     temp = the_max - k
            #     ans = []
            #     for pos in range(self.n):
            #         if(eq[pos] == 1):
            #             if(temp > 0):
            #                 ans.append(int(tot[pos] - 1))
            #                 temp -= 1
            #             else:
            #                 ans.append(int(tot[pos]))
            #         else:
            #             ans.append(int(tot[pos]))
            #     pass
            #     print(' '.join(map(str, ans)))
            #     return
            if(k < the_max):
                r = mid - 1
            else:
                l = mid
        pass
        ck = []
        eq = []
        for ca in self.a:
            t1,t2 = self.find_le(l+ca, ca)
            ck.append(t1)

        ck1 = []
        eq1 = 0
        for ca in self.a:
            t1,t2 = self.find_le(l+1+ca, ca)
            ck1.append(t1)
            eq1 += t2
        the_max = sum(ck1)
        the_min = the_max - eq1
        #assert(k<the_max and k>= the_min)

        res = k - sum(ck)
        for i in range(self.n):
            if(ck1[i]>ck[i]):
                if(res>0):
                    res-=1
                    ck[i] += 1
        pass
        print(' '.join(map(str, ck)))

    def main(self):
        self.find_k(self.k)
        pass

if __name__ == "__main__":
    cf = CF()
    cf.main()
    pass
```


1366_D. Two Divisors

You are given n integers a_1, a_2, ..., a_n.

For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair.

Input

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

The second line contains n integers a_1, a_2, ..., a_n (2 ≤ a_i ≤ 10^7) — the array a.

Output

To speed up the output, print two lines with n integers in each line.

The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them.

Example

Input

10
2 3 4 5 6 7 8 9 10 24

Output

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

Note

Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7.

There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them.

```python
import sys
from collections import deque, Counter
from itertools import product
from functools import reduce
input = sys.stdin.buffer.readline

n = int(input())
ls = list(map(int, input().split()))
mx = max(ls)

pr = [i for i in range(mx+1)]
for u in range(2, mx+1):
    if u*u > mx: break
    if pr[u] == u:
        for v in range(u*2, mx+1, u):
            pr[v] = min(pr[v], u)

def get_fac(n):
    fac = []
    while n > 1:
        p = pr[n]
        if not fac or fac[-1] != p: fac.append(p)
        n //= p
    return fac

d1, d2 = [], []
for u in ls:
    f = get_fac(u)
    if len(f) < 2:
        d1.append(-1)
        d2.append(-1)
    else:
        d1.append(f[0])
        d2.append(reduce(lambda x, y: x*y, f[1:]))
print(*d1)
print(*d2)

```


1387_A. Graph

You are given an undirected graph where each edge has one of two colors: black or red.

Your task is to assign a real number to each node so that:

  * for each black edge the sum of values at its endpoints is 1;
  * for each red edge the sum of values at its endpoints is 2;
  * the sum of the absolute values of all assigned numbers is the smallest possible.

Otherwise, if it is not possible, report that there is no feasible assignment of the numbers.

Input

The first line contains two integers N (1 ≤ N ≤ 100 000) and M (0 ≤ M ≤ 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, …, N.

The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 ≤ a, b ≤ N) with color c (1 denotes black, 2 denotes red).

Output

If there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 ≤ i ≤ N), the i-th number should be the number assigned to the node i.

Output should be such that:

  * the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6};
  * the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}.

If there are several valid solutions, output any of them.

If there is no solution, the only line should contain the word "NO".

Scoring

Subtasks:

  1. (5 points) N ≤ 5, M ≤ 14
  2. (12 points) N ≤ 100
  3. (17 points) N ≤ 1000
  4. (24 points) N ≤ 10 000
  5. (42 points) No further constraints

Examples

Input

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

Output

YES
0.5 0.5 1.5 -0.5

Input

2 1
1 2 1

Output

YES
0.3 0.7

Input

3 2
1 2 2
2 3 2

Output

YES
0 2 0

Input

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

Output

NO

Note

Note that in the second example the solution is not unique.

```python
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()

# ------------------------------

def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
    print(' '.join(map(str,l)))
# import heapq as hq
# import bisect as bs
# from collections import deque as dq
# from collections import defaultdict as dc
# from math import ceil,floor,sqrt
# from collections import Counter

n,m = RL()
dic = [[] for _ in range(n+1)]
for _ in range(m):
    u,v,t = RL()
    dic[u].append((v,t))
    dic[v].append((u,t))
v = [None] * (n+1)
f = [True] * (n+1)
key = {}
color = [0]*(n+1)
flag = True
for s in range(1,n+1):
    if v[s] is not None: continue
    v[s] = 0
    color[s] = s
    now = [s]
    ss = [0]
    while now and flag:
        p = now.pop()
        for child,t in dic[p]:
            if v[child] is not None:
                if f[child]!=f[p]:
                    if v[child]+v[p]!=t:
                        flag = False
                        break
                elif f[child] is True:
                    if s not in key:
                        key[s] =  (v[child]+v[p]-t)/(-2)
                    elif v[child]+v[p]+key[s]*2!=t:
                        flag = False
                        break
                else:
                    if s not in key:
                        key[s] =  (v[child]+v[p]-t)/2
                    elif v[child]+v[p]-key[s]*2!=t:
                        flag = False
                        break
            else:
                v[child] = t-v[p]
                f[child] = not f[p]
                if f[child]:
                    ss.append(-1*v[child])
                else:
                    ss.append(v[child])
                color[child] = s
                now.append(child)
    if not flag:
        break
    if s not in key:
        ss.sort()
        nn = len(ss)
        key[s] = (ss[nn>>1]+ss[nn-1>>1])/2
if flag:
    print("YES")
    res = []
    for i in range(1,n+1):
        if f[i]:
            res.append(v[i]+key[color[i]])
        else:
            res.append(v[i]-key[color[i]])
    print_list(res)
else:
    print("NO")
```


1408_D. Searchlights

There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m).

In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points.

Searchlight j can see a robber i if a_i ≤ c_j and b_i ≤ d_j.

A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i).

What is the minimum number of moves you need to perform to reach a safe configuration?

Input

The first line of input contains two integers n and m (1 ≤ n, m ≤ 2000): the number of robbers and the number of searchlight.

Each of the next n lines contains two integers a_i, b_i (0 ≤ a_i, b_i ≤ 10^6), coordinates of robbers.

Each of the next m lines contains two integers c_i, d_i (0 ≤ c_i, d_i ≤ 10^6), coordinates of searchlights.

Output

Print one integer: the minimum number of moves you need to perform to reach a safe configuration.

Examples

Input

1 1
0 0
2 3

Output

3

Input

2 3
1 6
6 1
10 1
1 10
7 7

Output

4

Input

1 2
0 0
0 0
0 0

Output

1

Input

7 3
0 8
3 8
2 7
0 10
5 5
7 0
3 5
6 6
3 11
11 5

Output

6

Note

In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0).

The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2.

In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3).

It's easy the see that the configuration of the robbers is safe.

It can be proved that you can't reach a safe configuration using no more than 3 moves.

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

robbers = []
lights = []

for i in range(n):
    a, b = map(int, input().split())
    robbers.append((a, b))

for i in range(m):
    c, d = map(int, input().split())
    lights.append((c, d))

C = [0] * 1000002

for a, b in robbers:
    for c, d in lights:
        if a <= c:
            C[c - a] = max(C[c - a], d - b + 1)

result = 1000001
max_value = 0

for i in range(1000001, -1, -1):
    max_value = max(max_value, C[i])
    result = min(result, i + max_value)

print(result)
```


1452_B. Toy Blocks

You are asked to watch your nephew who likes to play with toy blocks in a strange way.

He has n boxes and the i-th box has a_i blocks. His game consists of two steps:

  1. he chooses an arbitrary box i;
  2. he tries to move all blocks from the i-th box to other boxes.

If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.

You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put?

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 (2 ≤ n ≤ 10^5) — the number of boxes.

The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9) — the number of blocks in each box.

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

Output

For each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite.

Example

Input

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

Output

1
0
3

Note

In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks.

In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal.

In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1].

```python
from __future__ import division, print_function
import bisect
import math
import heapq
import itertools
import sys
from collections import deque
from atexit import register
from collections import Counter
from functools import reduce
if sys.version_info[0] < 3:
    from io import BytesIO as stream
else:
    from io import StringIO as stream

if sys.version_info[0] < 3:
    class dict(dict):
        """dict() -> new empty dictionary"""
        def items(self):
            """D.items() -> a set-like object providing a view on D's items"""
            return dict.iteritems(self)

        def keys(self):
            """D.keys() -> a set-like object providing a view on D's keys"""
            return dict.iterkeys(self)

        def values(self):
            """D.values() -> an object providing a view on D's values"""
            return dict.itervalues(self)

    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

def sync_with_stdio(sync=True):
    """Set whether the standard Python streams are allowed to buffer their I/O.

    Args:
        sync (bool, optional): The new synchronization setting.

    """
    global input, flush

    if sync:
        flush = sys.stdout.flush
    else:
        sys.stdin = stream(sys.stdin.read())
        input = lambda: sys.stdin.readline().rstrip('\r\n')

        sys.stdout = stream()
        register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))

def main():
    # sys.stdin  = open("input.txt")
    for _ in range(int(input())):
        n=int(input())
        a=[int(o) for o in input().split()]
        su = sum(a)
        ma = max(a)
        k = max(ma,math.ceil(su/(n-1)))
        print(k*(n-1)-su)

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


1475_G. Strange Beauty

Polycarp found on the street an array a of n elements.

Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i ≠ j:

  * a_i is divisible by a_j;
  * or a_j is divisible by a_i.

For example, if:

  * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met);
  * n=3 and a=[2, 14, 42], then the a array is beautiful;
  * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met);

Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful.

Input

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

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

The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2 ⋅ 10^5) — elements of the array a.

Output

For each test case output one integer — the minimum number of elements that must be removed to make the array a beautiful.

Example

Input

4
5
7 9 3 14 63
3
2 14 42
4
45 9 3 18
3
2 2 8

Output

2
0
1
0

Note

In the first test case, removing 7 and 14 will make array a beautiful.

In the second test case, the array a is already beautiful.

In the third test case, removing one of the elements 45 or 18 will make the array a beautiful.

In the fourth test case, the array a is beautiful.

```python
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
    def __init__(self, file):
        self.newlines = 0
        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()

# --------------------------------------------------------------------

def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))

# sys.setrecursionlimit(200000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# import math
# import bisect as bs
from collections import Counter
# from collections import defaultdict as dc

for t in range(N()):
    n = N()
    a = RLL()
    count = Counter(a)
    dp = [0] * 200001
    for i in range(1, 200001):
        if count[i] == 0: continue
        dp[i] += count[i]
        for j in range(2 * i, 200001, i):
            dp[j] = max(dp[i], dp[j])
    print(n - max(dp))

```


1526_A. Mean Inequality

You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours.

More formally, find an array b, such that:

  * b is a permutation of a.

  * For every i from 1 to 2n, b_i ≠ \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1.

It can be proved that under the constraints of this problem, such array b always exists.

Input

The first line of input contains a single integer t (1 ≤ t ≤ 1000) — the number of testcases. The description of testcases follows.

The first line of each testcase contains a single integer n (1 ≤ n ≤ 25).

The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≤ a_i ≤ 10^9) — elements of the array.

Note that there is no limit to the sum of n over all testcases.

Output

For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied.

Example

Input

3
3
1 2 3 4 5 6
2
123 456 789 10
1
6 9

Output

3 1 4 2 5 6
123 10 456 789
9 6

Note

In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)≠ 1, (1+2)/(2)≠ 4, (4+5)/(2)≠ 2, (2+6)/(2)≠ 5, (5+3)/(2)≠ 6, (6+1)/(2)≠ 3.

```python
for x in range(int(input())):
    n = int(input())
    m=list(map(int,input().split()))
    m.sort(reverse=True)
    a=[0]*2*n
    for i in range(n):
        a[2*i]=m[i]
    for i in range(n):
        a[2*i+1]=m[n+i]
    print(*a)
```


157_D. Suspects

As Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).

Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?

Input

The first line contains two integers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ n) — the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≤ ai ≤ n).

It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.

Output

Print n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.

Examples

Input

1 1
+1

Output

Truth

Input

3 2
-1
-2
-3

Output

Not defined
Not defined
Not defined

Input

4 1
+2
-3
+4
-1

Output

Lie
Not defined
Lie
Not defined

Note

The first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.

In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.

In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.

```python
"""
Brandt Smith, Lemuel Gorion and Peter Haddad

codeforces.com

Problem 156B
"""
import sys

n, m = map(int, input().split(' '))

inp = []
guess = [0] * (n + 1)

for i in range(n):
    temp = int(input())
    inp.append(temp)

    if temp < 0:
        m -= 1
        guess[-temp] -= 1
    else:
        guess[temp] += 1

dic = {temp for temp in range(1, n + 1) if guess[temp] == m}

if len(dic) == 0:
    for i in range(n):
        print('Not defined')
elif len(dic) == 1:
    temp = dic.pop()

    for i in inp:
        if i == temp or (i < 0 and i + temp):
            print('Truth')
        else:
            print('Lie')
else:
    temp = dic.update({-i for i in dic})

    for i in inp:
        if i in dic:
            print('Not defined')
        else:
            if i < 0:
                print('Truth')
            else:
                print('Lie')

# Made By Mostafa_Khaled
```


224_A. Parallelepiped

You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.

Input

The first and the single line contains three space-separated integers — the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement.

Output

Print a single number — the sum of all edges of the parallelepiped.

Examples

Input

1 1 1

Output

12

Input

4 6 6

Output

28

Note

In the first sample the parallelepiped has sizes 1 × 1 × 1, in the second one — 2 × 2 × 3.


248_D. Sweets for Everyone!

For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"

Dr. Suess, How The Grinch Stole Christmas

Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street.

The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets).

After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food.

The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets.

Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street.

Your task is to write a program that will determine the minimum possible value of k.

Input

The first line of the input contains two space-separated integers n and t (2 ≤ n ≤ 5·105, 1 ≤ t ≤ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop).

It is guaranteed that there is at least one segment with a house.

Output

If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k.

Examples

Input

6 6
HSHSHS

Output

1

Input

14 100
...HHHSSS...SH

Output

0

Input

23 50
HHSS.......SSHHHHHHHHHH

Output

8

Note

In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back.

In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction.

In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home.

```python
def check(n, casas):
    #print('n:',n)
    global T,N,street
    current = n
    time = T
    need = 0
    last_house = 0

    for ind, i in enumerate(street):
        time -= 1

        if i == 'S':
            current += 1

        elif i == 'H':
            need += 1
            if need == 1:
                last_house = ind

        if need > 0 and current >= need:
            #print('p',time, ind-last_house)
            current -= need
            casas -= need
            need = 0

            if casas > 0:
                if (ind-last_house)*2 >= N-last_house-1:
                    time -= N-last_house-1 + N-ind-1

                    return time >= 0

                time -= (ind-last_house)*2
            else:
                time -= ind-last_house

        #print('lugar:',i,ind,current, time, need, last_house)

        if casas == 0:
            break

    #print(time)
    return time >= 0 and casas == 0

N,T = [int(i) for i in input().split()]

street = input().rstrip('.')
N = len(street)
C = street.count('H')
S = street.count('S')
l = max(C-S, 0)
r = 500005
#print(N, C)
while l < r:
    mid = (l+r)//2
    if check(mid, C):
        r = mid
    else:
        l = mid + 1

print(l if l < 500005 else -1)
```


296_B. Yaroslav and Two Strings

Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≤ i, j ≤ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w.

A string's template is a string that consists of digits and question marks ("?").

Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers.

Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7).

Input

The first line contains integer n (1 ≤ n ≤ 105) — the length of both templates. The second line contains the first template — a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format.

Output

In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7).

Examples

Input

2
90
09

Output

1

Input

2
11
55

Output

0

Input

5
?????
?????

Output

993531194

Note

The first test contains no question marks and both strings are incomparable, so the answer is 1.

The second test has no question marks, but the given strings are comparable, so the answer is 0.

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

def build(n, s, t):
    ans = 1
    for i in range(n):
        if s[i] == '?' and t[i] == '?':
            ans = (55 * ans) % (10 ** 9 + 7)
        elif s[i] == '?':
            ans = ((ord(t[i]) - ord('0') + 1) * ans) % (10 ** 9 + 7)
        elif t[i] == '?':
            ans = ((ord('9') - ord(s[i]) + 1) * ans) % (10 ** 9 + 7)
    return ans

n = int(input())
s = input()
t = input()

sltt = True
tlts = True
qm = 0
cqm = 0
for i in range(n):
    if t[i] == '?':
        qm += 1
    if s[i] == '?':
        qm += 1
    if t[i] == '?' and s[i] == '?':
        cqm += 1
    if t[i] == '?' or s[i] == '?':
        continue
    if ord(s[i]) < ord(t[i]):
        tlts = False
    if ord(t[i]) < ord(s[i]):
        sltt = False

if not sltt and not tlts:
    print(pow(10, qm, 10 ** 9 + 7))
elif sltt and tlts:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 + 7))
elif sltt:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7))
else:
    print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7))

```


319_E. Ping-Pong

In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.

Your program should handle the queries of the following two types:

  1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals.
  2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval?

Answer all the queries. Note, that initially you have an empty set of intervals.

Input

The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value.

It's guaranteed that all queries are correct.

Output

For each query of the second type print "YES" or "NO" on a separate line depending on the answer.

Examples

Input

5
1 1 5
1 5 11
2 1 2
1 2 9
2 1 2

Output

NO
YES

```python
def dfs(G, start, path_exists):
    s = [start]
    visited = set([])
    if not start in path_exists:
        path_exists[start] = set([])

    while(s):
        node = s.pop()
        if not node in visited:
            visited.add(node)
            path_exists[start].add(node)
            a, b = G[node]

            for i, (c, d) in enumerate(G):
                if i != node:
                    if i in path_exists[start] or (c < a < d) or (c < b < d):
                        s.append(i)

if __name__ == "__main__":
    n = int(input())

    G = []
    path_exists = {}
    for _ in range(n):
        q, a, b = map(int, input().split())

        if q == 1:
            G.append((a, b))
        else:
            a -= 1
            b -= 1
            dfs(G, a, path_exists)
            if b in path_exists[a]:
                print("YES")
            else:
                print("NO")

```


367_B. Sereja ans Anagrams

Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.

Sereja needs to rush to the gym, so he asked to find all the described positions of q.

Input

The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).

Output

In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.

Examples

Input

5 3 1
1 2 3 2 1
1 2 3

Output

2
1 3

Input

6 3 2
1 3 2 2 3 1
1 2 3

Output

2
1 2

```python
from sys import stdin, stdout
from math import log, sqrt

lines = stdin.readlines()
n = int(lines[0].split()[0])
m = int(lines[0].split()[1])
p = int(lines[0].split()[2])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]

def hash_elem(x):
    x = (x * 1662634645 + 32544235) & 0xffffffff
    x = ((x >> 13) + (x << 19)) & 0xffffffff
    x = (x * 361352451) & 0xffffffff
    return x

c = [hash_elem(elem) for elem in a]

c_new = [sum([c[q + p * i] for i in range(m)]) for q in range(min(p, max(0, n - (m - 1) * p)))]
for q in range(p, n - (m - 1) * p):
    prev = c_new[q - p]
    # print(len(c_new)-1, q, q + p*(m-1))
    c_new.append(prev - c[q - p] + c[q + p * (m - 1)])

b_check = sum([hash_elem(elem) for elem in b])

ans1 = 0
ans = []
for q in range(n - (m - 1) * p):
    c_check = c_new[q]
    if b_check != c_check:
        continue
    else:
        ans1 += 1
        ans.append(q + 1)

print(ans1)
stdout.write(' '.join([str(x) for x in ans]))
```


40_E. Number Table

As it has been found out recently, all the Berland's current economical state can be described using a simple table n × m in size. n — the number of days in each Berland month, m — the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information — the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.

Input

The first line contains integers n and m (1 ≤ n, m ≤ 1000). The second line contains the integer k (0 ≤ k < max(n, m)) — the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≤ a ≤ n) — the number of the table row, b (1 ≤ b ≤ m) — the number of the column, c — the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≤ p ≤ 109 + 7).

Output

Print the number of different tables that could conform to the preserved data modulo p.

Examples

Input

2 2
0
100

Output

2

Input

2 2
1
1 1 -1
100

Output

1

```python
import itertools
import math

n, m = [int(x) for x in input().split()]
if n%2 != m%2:
    print(0)
else:
    k = int(input())
    S = [[] for i in range(max(n,m))]
    for i in range(k):
        a, b, c = [int(x) for x in input().split()]
        if n<m:
            S[b-1].append(c==-1)
        else:
            S[a-1].append(c==-1)

    p = int(input())
    restrictions = k
    for string in S:
        if len(string) >= min(n,m):
            if sum(string)%2:
                restrictions -= 1
            else:
                print(0)
                break
    else:
        print(pow(2, (n-1)*(m-1) - restrictions, p))

```


460_A. Vasya and Socks

Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?

Input

The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100), separated by a space.

Output

Print a single integer — the answer to the problem.

Examples

Input

2 2

Output

3

Input

9 3

Output

13

Note

In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two.

In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day.

```python
n, m = map(int, input().split() )
r = 0
t = 1
while n:
    n -= 1
    if t % m == 0:
        n += 1
    t += 1
print(t-1)

```


507_E. Breaking Good

Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.

Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads.

The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.

The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.

First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible.

Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional.

If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.

Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).

Can you help Walter complete his task and gain the gang's trust?

Input

The first line of input contains two integers n, m (2 ≤ n ≤ 105, <image>), the number of cities and number of roads respectively.

In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≤ x, y ≤ n, <image>) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not.

Output

In the first line output one integer k, the minimum possible number of roads affected by gang.

In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≤ x, y ≤ n, <image>), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up.

You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z.

After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n.

If there are multiple optimal answers output any.

Examples

Input

2 1
1 2 0

Output

1
1 2 1

Input

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

Output

3
1 2 0
1 3 1
2 3 0

Input

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

Output

3
2 3 0
1 5 0
6 8 1

Note

In the first test the only path is 1 - 2

In the second test the only shortest path is 1 - 3 - 4

In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8

```python
from collections import deque

def bfs(n, v, s, t):
    dis = [n] * n
    load = [n] * n
    path = [None] * n
    q = deque([s])
    dis[s] = 0
    load[s] = 0
    while (q):
        node = q.popleft()
        for i in range(len(v[node])):
            nb = v[node][i][0]
            status = v[node][i][1]
            tmp_dis = dis[node] + 1
            tmp_load = load[node] + (status != 1)
            if ((tmp_dis, tmp_load) < (dis[nb], load[nb])):
                dis[nb] = tmp_dis
                load[nb] = tmp_load
                path[nb] = node
                if (node != t): q.append(nb)
        if (node == t):
            break
    node = t
    opt = set()
    while (node != s):
        opt.add((min(node, path[node]), max(node, path[node])))
        node = path[node]
    return dis[t], load[t], opt

#def sp(s, t):
    ## dijkstra
    #global m, n, v, st, l_min, w_min, opt
    #current = s
    #visited = set([s])
    #dis = {}
    #dis[s] = 0
    #path = [[] for _ in xrange(n)]
    #path[s] = [[]]
    #load = [[] for _ in xrange(n)]
    #load[s] = [0]
    #while (current != t):
        #if (debug >= 2):
            #print 'current=%d' % current
        #for i in xrange(len(v[current])):
            #nb = v[current][i]
            #status = st[current][i]
            #if (debug >= 2):
                #print ' nb=%d, st=%d:' % (nb, status),
            #if (not dis.has_key(nb) or dis[nb] > 1 + dis[current]):
                ## update
                #dis[nb] = 1 + dis[current]
                #load[nb] = []
                #path[nb] = []
                #for j in xrange(len(load[current])):
                    #path[nb].append(path[current][j][:])
                    #path[nb][j].append((current, nb))
                    #if (status == 0):
                        #load[nb].append(load[current][j] + 1)
                    #else:
                        #load[nb].append(load[current][j])
                #if (debug >= 2):
                    #print 'Updated'
            #elif (dis[nb] == 1 + dis[current]):
                ## append
                #for j in xrange(len(load[current])):
                    #path[nb].append(path[current][j][:])
                    #path[nb][len(path[nb]) - 1].append((current, nb))
                    #if (status == 0): load[nb].append(1 + load[current][j])
                    #else: load[nb].append(load[current][j])
                #if (debug >= 2):
                    #print 'Appended'
            #else:
                #if (debug >= 2):
                    #print 'Passed'
        #sorted_idx = sorted(dis, key = dis.get)
        #if (debug >= 2): print sorted_idx
        #idx = 0
        #while (sorted_idx[idx] in visited): idx += 1
        #current = sorted_idx[idx]
        #visited.add(current)
    #w_min = min(load[t])
    #l_min = dis[t]
    #opt = tuple(path[t][load[t].index(w_min)])
    #return 0

#def dfs(s, t, visited, path, l, w):
    #global m, n, v, st, l_min, w_min, opt
    ##print path
    #if (s == t):
        #if (l < l_min):
            #l_min = l
            #w_min = w
            #opt = tuple(path)
        #else:
            #if (w < w_min):
                #w_min = w
                #opt = tuple(path)
        #return 0
    #if (l >= l_min): return 0
    ##if (w >= w_min): return 0
    #for i in xrange(len(v[s])):
        #if (v[s][i] in visited): continue
        #visited.add(v[s][i])
        #path.append((s, v[s][i]))
        #if (st[s][i] == 1):
            #dfs(v[s][i], t, visited, path, l + 1, w)
        #else:
            #dfs(v[s][i], t, visited, path, l + 1, w + 1)
        #visited.remove(v[s][i])
        #path.pop(len(path) - 1)
    #return 0

global debug
debug = 0

#global m, n, v, st, l_min, w_min
n, m = list(map(int, input().split()))
#e = []
v = [[] for _ in range(n)]
a = 0 # bad count
b = 0 # good count
#l_min = n
#w_min = n
#opt = ()
for i in range(m):
    v1, v2, status = list(map(int, input().split()))
    if (status == 0): a += 1
    else: b += 1
    v[v1 - 1].append((v2 - 1, status))
    v[v2 - 1].append((v1 - 1, status))
    #e.append((v1, v2, status))
if (debug >= 1): t0 = time.time()
#dfs(0, n - 1, set(), [], 0, 0)
#sp(n - 1, 0)
#sp(0, n - 1)
l_min, w_min, opt = bfs(n, v, 0, n - 1)
#l_min, w_min, opt = bfs(n, v, st, n - 1, 0)
print(b - l_min + 2 * w_min)
#print opt
#for i in xrange(len(e)):
#    if ((e[i][0] - 1, e[i][1] - 1) in opt or (e[i][1] - 1, e[i][0] - 1) in opt):
#        if (e[i][2] == 0): print '%d %d 1' % (e[i][0], e[i][1])
#    else:
#        if (e[i][2] == 1): print '%d %d 0' % (e[i][0], e[i][1])
#for i in xrange(len(e)):
#    if ((min(e[i][0] - 1, e[i][1] - 1), max(e[i][0] - 1, e[i][1] - 1)) in opt):
#        if (e[i][2] == 0): print '%d %d 1' % (e[i][0], e[i][1])
#    else:
#        if (e[i][2] == 1): print '%d %d 0' % (e[i][0], e[i][1])
for v1 in range(n):
    for v2, status in v[v1]:
        if (v2 < v1): continue
        if ((v1, v2) in opt):
            if (status == 0): print('%d %d 1' % (v1 + 1, v2 + 1))
        else:
            if (status == 1): print('%d %d 0' % (v1 + 1, v2 + 1))
if (debug >= 1): print('%f' % (time.time() - t0))

```


557_A. Ilya and Diplomas

Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.

At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma.

They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree.

After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree.

Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations.

It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree.

Input

The first line of the input contains a single integer n (3 ≤ n ≤ 3·106) — the number of schoolchildren who will participate in the Olympiad.

The next line of the input contains two integers min1 and max1 (1 ≤ min1 ≤ max1 ≤ 106) — the minimum and maximum limits on the number of diplomas of the first degree that can be distributed.

The third line of the input contains two integers min2 and max2 (1 ≤ min2 ≤ max2 ≤ 106) — the minimum and maximum limits on the number of diplomas of the second degree that can be distributed.

The next line of the input contains two integers min3 and max3 (1 ≤ min3 ≤ max3 ≤ 106) — the minimum and maximum limits on the number of diplomas of the third degree that can be distributed.

It is guaranteed that min1 + min2 + min3 ≤ n ≤ max1 + max2 + max3.

Output

In the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas.

The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree.

Examples

Input

6
1 5
2 6
3 7

Output

1 2 3

Input

10
1 2
1 3
1 5

Output

2 3 5

Input

6
1 3
2 2
2 2

Output

2 2 2

```python
ttl = int(input())
mx1 = [int(i) for i in list(input().split(" "))]
mx2 = [int(i) for i in list(input().split(" "))]
mx3 = [int(i) for i in list(input().split(" "))]
min1 = mx1[0]
min2 = mx2[0]
min3 = mx3[0]
max1 = mx1[1]-min1
max2 = mx2[1]-min2
max3 = mx3[1]-min3

ttl -=(mx1[0]+mx2[0]+mx3[0])
while(ttl>0):
    if(ttl>=(max1) and ttl>0):
        ttl -= max1
        min1+= max1
    else:
        min1 += ttl
        ttl = 0
    if(ttl>=(max2) and ttl>0):
        ttl -= max2
        min2+= max2
    else:
        min2 += ttl
        ttl = 0
    if(ttl>=(max3) and ttl>0):
        ttl -= max3
        min3+= max3
    else:
        min3 += ttl
        ttl = 0
print(str(min1)+" "+str(min2)+" "+str(min3))
```


604_D. Moodular Arithmetic

As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that

<image>

for some function <image>. (This equation should hold for any integer x in the range 0 to p - 1, inclusive.)

It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7.

Input

The input consists of two space-separated integers p and k (3 ≤ p ≤ 1 000 000, 0 ≤ k ≤ p - 1) on a single line. It is guaranteed that p is an odd prime number.

Output

Print a single integer, the number of distinct functions f modulo 109 + 7.

Examples

Input

3 2

Output

3

Input

5 4

Output

25

Note

In the first sample, p = 3 and k = 2. The following functions work:

  1. f(0) = 0, f(1) = 1, f(2) = 2.
  2. f(0) = 0, f(1) = 2, f(2) = 1.
  3. f(0) = f(1) = f(2) = 0.

```python
MOD = 10**9+7
def f(a,b):
    if b == 1:
        return a%MOD
    elif b % 2 == 0:
        return f((a*a)%MOD,b//2)
    else:
        return (a*f((a*a)%MOD,b//2)) % MOD

p,k = map(int,input().split())
if k == 0:
    print(f(p,p-1))
    exit()
if k == 1:
    print(f(p,p))
    exit()
t = 1
a = k
while a != 1:
    a = (a*k % p)
    t += 1
n = (p-1)//t
print(f(p,n))

```


676_C. Vasya and String

High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.

Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

Input

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change.

The second line contains the string, consisting of letters 'a' and 'b' only.

Output

Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

Examples

Input

4 2
abba

Output

4

Input

8 1
aabaabaa

Output

5

Note

In the first sample, Vasya can obtain both strings "aaaa" and "bbbb".

In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".

```python

#########			##	##     ##    	  ####  #####  ##     #  ##     #		##
	#			   # #	# #   # #		 #	  #	#	#  # #    #  # #    #	   # #
	#			  #  #	#  ###  #	    #		#	#  #  #   #  #  #   #	  #  #
	#			 #####	#	#	#	   #    ###	#	#  #   #  #  #   #  #    #####
	#			#    #	#		#	   #    # #	#	#  #	# #  #	  # #   #    #
######### 	   #     # 	#		#		##### #	#####  #	 ##  #	   ##  #     #

"""

PPPPPPP       RRRRRRR		    OOOO	  VV        VV    EEEEEEEEEE
PPPPPPPP      RRRRRRRR         OOOOOO     VV       VV	  EE
PPPPPPPPP     RRRRRRRRR       OOOOOOOO    VV      VV	  EE
PPPPPPPP      RRRRRRRR        OOOOOOOO    VV     VV    	  EEEEEE
PPPPPPP       RRRRRRR         OOOOOOOO    VV    VV        EEEEEEE
PP  		  RRRR			  OOOOOOOO    VV   VV         EEEEEE
PP			  RR  RR          OOOOOOOO    VV  VV          EE
PP			  RR    RR         OOOOOO     VV VV           EE
PP			  RR      RR        OOOO      VVVV            EEEEEEEEEE

"""

"""
 Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
import sys
input = sys.stdin.readline
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;

def ceil(x):
    if x != int(x):
        x = int(x) + 1
    return x

def factorial(x, m):
	val = 1
	while x>0:
		val = (val * x) % m
		x -= 1
	return val

# swap_array function
def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;

## gcd function
def gcd(a,b):
    if b == 0:
        return a;
    return gcd(b, a % b);

## nCr function efficient using Binomial Cofficient
def nCr(n, k):
    if(k > n - k):
        k = n - k;
    res = 1;
    for i in range(k):
        res = res * (n - i);
        res = res / (i + 1);
    return int(res);

## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0, hi = None):
    if hi == None:
        hi = len(a);
    while lo < hi:
        mid = (lo+hi)//2;
        if a[mid] < x:
            lo = mid+1;
        else:
            hi = mid;
    return lo;

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    primes = {}
    while(n%2 == 0 and n > 0):
        primes[2] = primes.get(2, 0) + 1
        n = n//2
    for i in range(3, int(n**0.5)+2, 2):
        while(n%i == 0 and n > 0):
            primes[i] = primes.get(i, 0) + 1
            n = n//i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
    res = 1
    x = x % p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) :
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b;

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
def find(x, link):
    p = x;
    while( p != link[p]):
        p = link[p];

    while( x != p):
        nex = link[x];
        link[x] = p;
        x = nex;
    return p;

# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        x,y = swap(x,y)
    if x != y:
        size[x] += size[y]
        link[y] = x

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    return prime

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
    spf[1] = 1;
    for i in range(2, MAXN):
        spf[i] = i;
    for i in range(4, MAXN, 2):
        spf[i] = 2;
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i*i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret;
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()));

def float_array():
    return list(map(float, input().strip().split()));

## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

from itertools import permutations
import math

def possible(freq, l, k):
	for i in range(l, len(freq)):
		val = freq[i] - freq[i - l]
		alt = l - val
		if val + k >= l or alt + k >= l:
			return True
	return False

def solve():
	maxim = 0
	n, k = map(int, input().split())
	s = list(input())
	if s[-1] == '\n':
		s.pop()
	freq = [0]
	for x in s:
		if x == 'a':
			if len(freq) == 0:
				freq.append(1)
			else:
				freq.append(freq[-1] + 1)
		else:
			freq.append(freq[-1])
	# print(freq)
	low, high = 0, n + 1
	while low < high:
		mid = (high - low) // 2 + low
		if possible(freq, mid, k):
			maxim = max(maxim, mid)
			low = mid + 1

		else:
			high = mid

	print(maxim)

if __name__ == '__main__':
	for _ in range(1):
		solve()
	# fin_time = datetime.now()
# 	print("Execution time (for loop): ", (fin_time-init_time))

```


69_C. Game

In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts.

After the composing composite artifact, all the components disappear.

Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts.

Input

The first line has 4 natural numbers: k (1 ≤ k ≤ 100) — the number of Kostya's allies, n (1 ≤ n ≤ 50) — the number of basic artifacts, m (0 ≤ m ≤ 50) — the number of composite artifacts, q (1 ≤ q ≤ 500) — the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format:

<Art. Name>: <Art. №1> <Art. №1 Number>, <Art. №2> <Art. №2 Number>, ... <Art. №X> <Art. №Х Number>

All the numbers are natural numbers not exceeding 100 (1 ≤ X ≤ n).

The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts.

Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≤ ai ≤ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there.

It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it.

Output

The output file should consist of k blocks. The first line should contain number bi — the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive.

Examples

Input

2 3 2 5
desolator
refresher
perseverance
vanguard: desolator 1, refresher 1
maelstorm: perseverance 2
1 desolator
2 perseverance
1 refresher
2 desolator
2 perseverance

Output

1
vanguard 1
2
desolator 1
maelstorm 1

```python
# Not really fair, since I already solved this one previously. ;)

k, n, m, q = [int(i) for i in input().split()]
basic = [input() for i in range(n)]

composite = {}
for i in range(m):
	name, items = input().split(":")
	composite[name] = {}
	for item in items.split(","):
		component, cnt = item.split()
		composite[name][component] = int(cnt)

friends = {}
for i in range(1, k+1):
	friends[str(i)] = {}
	for artifact in basic:
		friends[str(i)][artifact] = 0
	for artifact in composite.keys():
		friends[str(i)][artifact] = 0

for i in range(q):
	ai, artifact = input().split()
	friends[ai][artifact] += 1
	for artifact, combo in composite.items():
		if all(friends[ai][basic]==cnt for basic, cnt in combo.items()):
			for basic, cnt in combo.items():
				friends[ai][basic] -= cnt
			friends[ai][artifact] += 1
			break

for i in range(1, k+1):
	print(sum([i>0 for i in friends[str(i)].values()]))
	for artifact in sorted(friends[str(i)].keys()):
		if friends[str(i)][artifact] > 0:
			print(artifact, friends[str(i)][artifact])
```


742_C. Arpa's loud Owf and Mehrdad's evil plan

As you have noticed, there are lovely girls in Arpa’s land.

People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.

<image>

Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.

The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.

Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t ≥ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.

Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i).

Input

The first line of input contains integer n (1 ≤ n ≤ 100) — the number of people in Arpa's land.

The second line contains n integers, i-th of them is crushi (1 ≤ crushi ≤ n) — the number of i-th person's crush.

Output

If there is no t satisfying the condition, print -1. Otherwise print such smallest t.

Examples

Input

4
2 3 1 4

Output

3

Input

4
4 4 4 4

Output

-1

Input

4
2 1 4 3

Output

1

Note

In the first sample suppose t = 3.

If the first person starts some round:

The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1.

The process is similar for the second and the third person.

If the fourth person starts some round:

The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4.

In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa.

```python
from math import gcd

def DFS(v):
    re = 0
    cur = v
    while not used[cur]:
        used[cur] = True
        re += 1
        cur = gr[cur]
    if re % 2 == 0:
        re //= 2
    return 0 if cur != v else re

n = int(input())
used = [False] * (n + 1)
gr = [0] + list(map(int, input().split()))
res = 1
for u in range(1, len(gr)):
    if not used[u]:
        r = DFS(u)
        if r:
            res = (res * r) // gcd(res, r)
        else:
            print(-1)
            exit()
print(res)
```


810_A. Straight «A»

Noora is a student of one famous high school. It's her final year in school — she is going to study in university next year. However, she has to get an «A» graduation certificate in order to apply to a prestigious one.

In school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from 1 to k. The worst mark is 1, the best is k. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, 7.3 is rounded to 7, but 7.5 and 7.8784 — to 8.

For instance, if Noora has marks [8, 9], then the mark to the certificate is 9, because the average is equal to 8.5 and rounded to 9, but if the marks are [8, 8, 9], Noora will have graduation certificate with 8.

To graduate with «A» certificate, Noora has to have mark k.

Noora got n marks in register this year. However, she is afraid that her marks are not enough to get final mark k. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from 1 to k. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to k.

Input

The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 100) denoting the number of marks, received by Noora and the value of highest possible mark.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ k) denoting marks received by Noora before Leha's hack.

Output

Print a single integer — minimal number of additional marks, that Leha has to add in order to change Noora's final mark to k.

Examples

Input

2 10
8 9

Output

4

Input

3 5
4 4 4

Output

3

Note

Consider the first example testcase.

Maximal mark is 10, Noora received two marks — 8 and 9, so current final mark is 9. To fix it, Leha can add marks [10, 10, 10, 10] (4 marks in total) to the registry, achieving Noora having average mark equal to <image>. Consequently, new final mark is 10. Less number of marks won't fix the situation.

In the second example Leha can add [5, 5, 5] to the registry, so that making average mark equal to 4.5, which is enough to have 5 in the certificate.

```python
n,k=tuple(int(i) for i in input().strip().split(" "))
a=input().strip().split(" ")
sum=0
o=0
for i in a:
    sum+=int(i)
if sum/n>=k-0.5:
    print(0)
    exit(0)
while sum/n<k-0.5:
    sum+=k
    n+=1
    o+=1
print(o)
```