1073_F. Choosing Two Paths

You are given an undirected unweighted tree consisting of n vertices.

An undirected tree is a connected undirected graph with n - 1 edges.

Your task is to choose two pairs of vertices of this tree (all the chosen vertices should be distinct) (x_1, y_1) and (x_2, y_2) in such a way that neither x_1 nor y_1 belong to the simple path from x_2 to y_2 and vice versa (neither x_2 nor y_2 should not belong to the simple path from x_1 to y_1).

It is guaranteed that it is possible to choose such pairs for the given tree.

Among all possible ways to choose such pairs you have to choose one with the maximum number of common vertices between paths from x_1 to y_1 and from x_2 to y_2. And among all such pairs you have to choose one with the maximum total length of these two paths.

It is guaranteed that the answer with at least two common vertices exists for the given tree.

The length of the path is the number of edges in it.

The simple path is the path that visits each vertex at most once.

Input

The first line contains an integer n — the number of vertices in the tree (6 ≤ n ≤ 2 ⋅ 10^5).

Each of the next n - 1 lines describes the edges of the tree.

Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).

It is guaranteed that the given edges form a tree.

It is guaranteed that the answer with at least two common vertices exists for the given tree.

Output

Print any two pairs of vertices satisfying the conditions described in the problem statement.

It is guaranteed that it is possible to choose such pairs for the given tree.

Examples

Input

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

Output

3 6
7 5

Input

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

Output

2 9
6 8

Input

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

Output

10 6
4 5

Input

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

Output

9 11
8 10

Note

The picture corresponding to the first example: <image>

The intersection of two paths is 2 (vertices 1 and 4) and the total length is 4 + 3 = 7.

The picture corresponding to the second example: <image>

The intersection of two paths is 2 (vertices 3 and 4) and the total length is 5 + 3 = 8.

The picture corresponding to the third example: <image>

The intersection of two paths is 3 (vertices 2, 7 and 8) and the total length is 5 + 5 = 10.

The picture corresponding to the fourth example: <image>

The intersection of two paths is 5 (vertices 1, 2, 3, 4 and 5) and the total length is 6 + 6 = 12.

```python
import sys

n = int(sys.stdin.readline())
edges = [[] for _ in range(n)]
for _ in range(n - 1):
    i, j = tuple(int(k) for k in sys.stdin.readline().split())
    i -= 1
    j -= 1
    edges[i].append(j)
    edges[j].append(i)

# Prunes the graph starting from the vertices with
# only 1 edge until we reach a vertex with 3+ edges.
# Stores the distance from each non-pruned vertex
# to each of the leaves it reaches.
def prune():
    pruned = [False for _ in range(n)]
    leaves = [[] for _ in range(n)]
    todo = []
    for i in range(n):
        if len(edges[i]) == 1:
            todo.append((0, i, i))
    while len(todo) > 0:
        d, i, j = todo.pop()
        pruned[j] = True
        for k in edges[j]:
            if not pruned[k]:
                if len(edges[k]) < 3:
                    todo.append((d + 1, i, k))
                else:
                    leaves[k].append((d + 1, i))
    return pruned, leaves

pruned, leaves = prune()

# Returns the furthest non-pruned vertices
# from another non-pruned vertex.
def furthest(i):
    assert not pruned[i]
    visited = list(pruned)
    top_distance = 0
    top_vertices = [i]
    todo = [(0, i)]
    while len(todo) > 0:
        d, i = todo.pop()
        visited[i] = True
        if d > top_distance:
            top_distance = d
            top_vertices = []
        if d == top_distance:
            top_vertices.append(i)
        for j in edges[i]:
            if not visited[j]:
                todo.append((d + 1, j))
    return top_distance, top_vertices

# Single center topology.
# Only 1 vertex with 3+ edges.
def solve_single_center(i):
    l = list(reversed(sorted(leaves[i])))[:4]
    return list(l[j][1] for j in range(4))

# Scores non-pruned vertices according to the sum
# of the distances to their two furthest leaves.
def vertices_score(v):
    scores = []
    for i in v:
        assert not pruned[i]
        l = list(reversed(sorted(leaves[i])))[:2]
        score = (l[0][0] + l[1][0]), l[0][1], l[1][1]
        scores.append(score)
    return list(reversed(sorted(scores)))

# Single cluster topology.
# 1 cluster of vertices, all equally far away from each other.
def solve_single_cluster(v):
    scores = vertices_score(v)[:2]
    return scores[0][1], scores[1][1], scores[0][2], scores[1][2]

# Double cluster topology.
# 2 clusters of vertices, pairwise equally far away from each other.
def solve_double_cluster(v1, v2):
    scores1 = vertices_score(v1)[:1]
    scores2 = vertices_score(v2)[:1]
    return scores1[0][1], scores2[0][1], scores1[0][2], scores2[0][2]

def solve():
    def start_vertex():
        for i in range(n):
            if not pruned[i]:
                return i
    i = start_vertex()
    distance, v1 = furthest(i)
    if distance == 0:
        return solve_single_center(v1[0])
    else:
        distance, v1 = furthest(v1[0])
        distance, v2 = furthest(v1[0])
        v = list(set(v1) | set(v2))
        if len(v) < len(v1) + len(v2):
            return solve_single_cluster(v)
        else:
            return solve_double_cluster(v1, v2)

a, b, c, d = solve()
print(a + 1, b + 1)
print(c + 1, d + 1)

```


1095_F. Make It Connected

You are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.

You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.

What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.

Input

The first line contains two integers n and m (1 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the graph and the number of special offers, respectively.

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^{12}) — the numbers written on the vertices.

Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^{12}, x ≠ y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.

Output

Print one integer — the minimum number of coins you have to pay to make the graph connected.

Examples

Input

3 2
1 3 3
2 3 5
2 1 1

Output

5

Input

4 0
1 3 3 7

Output

16

Input

5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15

Output

18

Note

In the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.

In next two examples the optimal answer may be achieved without using special offers.

```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
e = []
for _ in range(m) :
    u, v, w = map(int, input().split())
    e.append((u-1, v-1, w))
a = sorted(zip(a, range(n)), key = lambda x : x[0])
for i in range(1, n) :
    e.append((a[0][1], a[i][1], a[0][0] + a[i][0]))

fa = list(range(n))
rk = [0] * n

def find(x) :
    while fa[x] != x :
        fa[x] = fa[fa[x]]
        x = fa[x]
    return x

def unite(u, v) :
    u, v = map(find, (u, v))
    if u == v : return False
    if rk[u] < rk[v] : u, v = v, u
    fa[v] = u
    if rk[u] == rk[v] : rk[u] += 1
    return True

e.sort(key = lambda x : x[2])

ans = 0
cnt = 1
for ee in e :
    if cnt == n : break
    if unite(ee[0], ee[1]) :
        ans += ee[2]
        cnt += 1

print(ans)
```


1117_A. Best Subsegment

You are given array a_1, a_2, ..., a_n. Find the subsegment a_l, a_{l+1}, ..., a_r (1 ≤ l ≤ r ≤ n) with maximum arithmetic mean (1)/(r - l + 1)∑_{i=l}^{r}{a_i} (in floating-point numbers, i.e. without any rounding).

If there are many such subsegments find the longest one.

Input

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

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

Output

Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean.

Example

Input

5
6 1 6 6 0

Output

2

Note

The subsegment [3, 4] is the longest among all subsegments with maximum arithmetic mean.

```python
n=int(input())
s=[int(x) for x in input().split()]
el=max(s)
pos1=-1
pos2=-1
c=0
ans=0
for i in range(0,len(s)):
    if(s[i]==el):
        c=c+1
    else:
        ans=max(ans,c)
        c=0
ans=max(ans,c)
print(ans)

```


1143_C. Queen

You are given a rooted tree with vertices numerated from 1 to n. A tree is a connected graph without cycles. A rooted tree has a special vertex named root.

Ancestors of the vertex i are all vertices on the path from the root to the vertex i, except the vertex i itself. The parent of the vertex i is the nearest to the vertex i ancestor of i. Each vertex is a child of its parent. In the given tree the parent of the vertex i is the vertex p_i. For the root, the value p_i is -1.

<image> An example of a tree with n=8, the root is vertex 5. The parent of the vertex 2 is vertex 3, the parent of the vertex 1 is vertex 5. The ancestors of the vertex 6 are vertices 4 and 5, the ancestors of the vertex 7 are vertices 8, 3 and 5

You noticed that some vertices do not respect others. In particular, if c_i = 1, then the vertex i does not respect any of its ancestors, and if c_i = 0, it respects all of them.

You decided to delete vertices from the tree one by one. On each step you select such a non-root vertex that it does not respect its parent and none of its children respects it. If there are several such vertices, you select the one with the smallest number. When you delete this vertex v, all children of v become connected with the parent of v.

<image> An example of deletion of the vertex 7.

Once there are no vertices matching the criteria for deletion, you stop the process. Print the order in which you will delete the vertices. Note that this order is unique.

Input

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

The next n lines describe the tree: the i-th line contains two integers p_i and c_i (1 ≤ p_i ≤ n, 0 ≤ c_i ≤ 1), where p_i is the parent of the vertex i, and c_i = 0, if the vertex i respects its parents, and c_i = 1, if the vertex i does not respect any of its parents. The root of the tree has -1 instead of the parent index, also, c_i=0 for the root. It is guaranteed that the values p_i define a rooted tree with n vertices.

Output

In case there is at least one vertex to delete, print the only line containing the indices of the vertices you will delete in the order you delete them. Otherwise print a single integer -1.

Examples

Input

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

Output

1 2 4

Input

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

Output

-1

Input

8
2 1
-1 0
1 0
1 1
1 1
4 0
5 1
7 0

Output

5

Note

The deletion process in the first example is as follows (see the picture below, the vertices with c_i=1 are in yellow):

  * first you will delete the vertex 1, because it does not respect ancestors and all its children (the vertex 2) do not respect it, and 1 is the smallest index among such vertices;
  * the vertex 2 will be connected with the vertex 3 after deletion;
  * then you will delete the vertex 2, because it does not respect ancestors and all its children (the only vertex 4) do not respect it;
  * the vertex 4 will be connected with the vertex 3;
  * then you will delete the vertex 4, because it does not respect ancestors and all its children (there are none) do not respect it ([vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth));
  * you will just delete the vertex 4;
  * there are no more vertices to delete.

<image>

In the second example you don't need to delete any vertex:

  * vertices 2 and 3 have children that respect them;
  * vertices 4 and 5 respect ancestors.

<image>

In the third example the tree will change this way:

<image>

```python
"""
https://codeforces.com/problemset/problem/1143/C
"""

n = int(input())

respect = [0 for _ in range(n)]
child_respect = [0 for _ in range(n)]

root = -1

for i in range(n):
    p, c = map(int,input().split())
    if p == -1:
        root = i
        continue
    respect[i] = c
    if p != -1 and not c: child_respect[p-1]=1

res = []
for i in range(n):
    if i == root:
        continue
    if respect[i] and not child_respect[i]:
        res.append(i+1)

if res:
    print(*res)
else:
    print(-1)
```


1163_C1. Power Transmission (Easy Edition)

This problem is same as the next one, but has smaller constraints.

It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.

At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates (x_i, y_i). Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.

Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

Input

The first line contains a single integer n (2 ≤ n ≤ 50) — the number of electric poles.

Each of the following n lines contains two integers x_i, y_i (-10^4 ≤ x_i, y_i ≤ 10^4) — the coordinates of the poles.

It is guaranteed that all of these n points are distinct.

Output

Print a single integer — the number of pairs of wires that are intersecting.

Examples

Input

4
0 0
1 1
0 3
1 2

Output

14

Input

4
0 0
0 2
0 4
2 0

Output

6

Input

3
-1 -1
1 0
3 1

Output

0

Note

In the first example:

<image>

In the second example:

<image>

Note that the three poles (0, 0), (0, 2) and (0, 4) are connected by a single wire.

In the third example:

<image>

```python
import sys
import collections
import math
import heapq
from operator import itemgetter

def getint():
    return int(input())

def getints():
    return [int(x) for x in input().split(' ')]

n = getint()
points = [tuple(getints()) for _ in range(n)]
result = 0

slopes = collections.defaultdict(set)
for i in range(n - 1):
    for j in range(i + 1, n):
        x1, y1, x2, y2 = points[i][0], points[i][1], points[j][0], points[j][1]
        a, b = y1 - y2, x1 - x2

        d = math.gcd(a, b)
        a, b = a // d, b // d
        if a < 0 or (a == 0 and b < 0):
            a, b = -a, -b

        c = a * x1 - b * y1
        slope = (a, b)
        slopes[slope].add(c)

slopeGroups = [(ab[0], ab[1], len(cs)) for ab, cs in slopes.items()]
m = len(slopeGroups)

for i in range(m - 1):
    intersects = 0
    for j in range(i + 1, m):
        intersects += slopeGroups[j][2]
    result += slopeGroups[i][2] * intersects

print(str(result))
```


1184_A1. Heidi Learns Hashing (Easy)

Melody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor.

Heidi figured out that Madame Kovarian uses a very complicated hashing function in order to change the names of the babies she steals. In order to prevent this from happening to future Doctors, Heidi decided to prepare herself by learning some basic hashing techniques.

The first hashing function she designed is as follows.

Given two positive integers (x, y) she defines H(x,y):=x^2+2xy+x+1.

Now, Heidi wonders if the function is reversible. That is, given a positive integer r, can you find a pair (x, y) (of positive integers) such that H(x, y) = r?

If multiple such pairs exist, output the one with smallest possible x. If there is no such pair, output "NO".

Input

The first and only line contains an integer r (1 ≤ r ≤ 10^{12}).

Output

Output integers x, y such that H(x,y) = r and x is smallest possible, or "NO" if no such pair exists.

Examples

Input

19

Output

1 8

Input

16

Output

NO

```python
from math import sqrt

def get_int():
    from sys import stdin
    return int(stdin.readline().replace('\n', ''))

def is_even(n):
    return n%2 == 0

def heidi_hash(r):
    k = r-1
    rt = int(sqrt(k))

    for x in range(1, rt+2):
        if k % x == 0:
            temp = k/x -x -1
            if temp > 0 and is_even(temp):
                return x,int(temp/2)
    return 'NO'

r = get_int()
res = heidi_hash(r)
print(res[0],res[1]) if type(res) != type('') else print(res)

```


1201_D. Treasure Hunting

You are on the island which can be represented as a n × m table. The rows are numbered from 1 to n and the columns are numbered from 1 to m. There are k treasures on the island, the i-th of them is located at the position (r_i, c_i).

Initially you stand at the lower left corner of the island, at the position (1, 1). If at any moment you are at the cell with a treasure, you can pick it up without any extra time. In one move you can move up (from (r, c) to (r+1, c)), left (from (r, c) to (r, c-1)), or right (from position (r, c) to (r, c+1)). Because of the traps, you can't move down.

However, moving up is also risky. You can move up only if you are in a safe column. There are q safe columns: b_1, b_2, …, b_q. You want to collect all the treasures as fast as possible. Count the minimum number of moves required to collect all the treasures.

Input

The first line contains integers n, m, k and q (2 ≤ n,   m,   k,   q ≤ 2 ⋅ 10^5, q ≤ m) — the number of rows, the number of columns, the number of treasures in the island and the number of safe columns.

Each of the next k lines contains two integers r_i, c_i, (1 ≤ r_i ≤ n, 1 ≤ c_i ≤ m) — the coordinates of the cell with a treasure. All treasures are located in distinct cells.

The last line contains q distinct integers b_1, b_2, …, b_q (1 ≤ b_i ≤ m) — the indices of safe columns.

Output

Print the minimum number of moves required to collect all the treasures.

Examples

Input

3 3 3 2
1 1
2 1
3 1
2 3

Output

6

Input

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

Output

8

Input

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

Output

15

Note

In the first example you should use the second column to go up, collecting in each row treasures from the first column.

<image>

In the second example, it is optimal to use the first column to go up.

<image>

In the third example, it is optimal to collect the treasure at cell (1;6), go up to row 2 at column 6, then collect the treasure at cell (2;2), go up to the top row at column 1 and collect the last treasure at cell (3;4). That's a total of 15 moves.

<image>

```python
from sys import stdin
from bisect import bisect_left
input=stdin.readline
n,m,k,q=map(int,input().split(' '))
x=sorted(list(map(int,input().split(' ')))for i in range(k))
y=sorted(list(map(int,input().split(' '))))
def rr(c0,c1,c2):
    return abs(c2-c0)+abs(c1-c2)

def tm(c0,c1):
    t=bisect_left(y,c0)
    tt=[]
    if (t>0):
        tt.append(rr(c0,c1,y[t-1]))
    if (t<q):
        tt.append(rr(c0,c1,y[t]))
    return min(tt)

# thực hiện tìm xem trong một hàng, kho báu nằm từ khoảng nào đến khoảng nào.
z=[]
for r,c in x:
    if z and z[-1][0]==r:
        z[-1][2]=c
    else:
        z.append([r,c,c])
v1,v2,r0,c01,c02=0,0,1,1,1
for r1,c11,c12 in z:
    d=c12-c11+r1-r0
    # bình thường
    if(r1>r0):
        d01=tm(c01,c11)
        d02=tm(c01,c12)
        d11=tm(c02,c11)
        d12=tm(c02,c12)
        v2,v1=d+min(v1+d01,v2+d11),d +min(v1+d02,v2+d12)

    #nếu có kho báu ở hàng 1
    else:
        v1,v2=d+c12-c02,d+c11-c01
    c01,c02,r0=c11,c12,r1
ans=min(v1,v2)
print(ans)

```


1219_C. Periodic integer number

Alice became interested in periods of integer numbers. We say positive X integer number is periodic with length L if there exists positive integer number P with L digits such that X can be written as PPPP…P. For example:

X = 123123123 is periodic number with length L = 3 and L = 9

X = 42424242 is periodic number with length L = 2,L = 4 and L = 8

X = 12345 is periodic number with length L = 5

For given positive period length L and positive integer number A, Alice wants to find smallest integer number X strictly greater than A that is periodic with length L.

Input

First line contains one positive integer number L \ (1 ≤ L ≤ 10^5) representing length of the period. Second line contains one positive integer number A \ (1 ≤ A ≤ 10^{100 000}).

Output

One positive integer number representing smallest positive number that is periodic with length L and is greater than A.

Examples

Input

3
123456

Output

124124

Input

3
12345

Output

100100

Note

In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).

In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)

```python
import math as m

def main():
	n = int(input())
	s = input()
	l = len(s)
	p = int(m.ceil(l/n))
	if l%n!=0 :
		t = '1'
		for i in range(1,n):
			t+='0'
		for i in range(0,p):
			print(t ,end = '')
	else :
		z = s[0:n]
		t=''
		for i in range(0,p):
			t+=z
		if t > s:
			print(t)
			return

		z = str(int(s[0:n])+1)
		if len(z)>n :
			t = '1'
			for i in range(1,n):
				t+='0'
			for i in range(0,p+1):
				print(t ,end = '')
			return

		t=''
		for i in range(0,p):
			t+=z

		print(t)

main()

```


1243_C. Tile Painting

Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.

The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers i and j, such that |j - i| is a divisor of n greater than 1, they have the same color. Formally, the colors of two tiles with numbers i and j should be the same if |i-j| > 1 and n mod |i-j| = 0 (where x mod y is the remainder when dividing x by y).

Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?

Input

The first line of input contains a single integer n (1 ≤ n ≤ 10^{12}), the length of the path.

Output

Output a single integer, the maximum possible number of colors that the path can be painted in.

Examples

Input

4

Output

2

Input

5

Output

5

Note

In the first sample, two colors is the maximum number. Tiles 1 and 3 should have the same color since 4 mod |3-1| = 0. Also, tiles 2 and 4 should have the same color since 4 mod |4-2| = 0.

In the second sample, all five colors can be used.

<image>

```python
def prime_factor(n):
    ass = []
    for i in range(2,int(n**0.5)+1):
        while n % i==0:
            ass.append(i)
            n = n//i
    if n != 1:
        ass.append(n)
    return ass

n = int(input())
p = list(set(prime_factor(n)))

if len(p) == 1:
    print(p[0])
else:
    print(1)
```


1263_B. PIN Codes

A PIN code is a string that consists of exactly 4 digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.

Polycarp has n (2 ≤ n ≤ 10) bank cards, the PIN code of the i-th card is p_i.

Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all n codes would become different.

Formally, in one step, Polycarp picks i-th card (1 ≤ i ≤ n), then in its PIN code p_i selects one position (from 1 to 4), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different.

Polycarp quickly solved this problem. Can you solve it?

Input

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

The first line of each of t test sets contains a single integer n (2 ≤ n ≤ 10) — the number of Polycarp's bank cards. The next n lines contain the PIN codes p_1, p_2, ..., p_n — one per line. The length of each of them is 4. All PIN codes consist of digits only.

Output

Print the answers to t test sets. The answer to each set should consist of a n + 1 lines

In the first line print k — the least number of changes to make all PIN codes different. In the next n lines output the changed PIN codes in the order corresponding to their appearance in the input. If there are several optimal answers, print any of them.

Example

Input

3
2
1234
0600
2
1337
1337
4
3139
3139
3139
3139

Output

0
1234
0600
1
1337
1237
3
3139
3138
3939
6139

```python
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
# from math import gcd
# from itertools import combinations,permutations,accumulate, product # (string,3) 3回
# #from collections import deque
# from collections import deque,defaultdict,Counter
# import decimal
# import re
# import math
# import bisect
# import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
# import sys
# sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
INF = float('inf')
# from sys import stdin
# readline = stdin.readline
def readInts():
  return list(map(int,input().split()))
def readTuples():
    return tuple(map(int,input().split()))
def I():
    return int(input())
q = I()
from collections import Counter,defaultdict

for _ in range(q):
    n = I()
    S = [input() for _ in range(n)]
    dic = Counter(S)
    ans = 0
    next = defaultdict(int)
    for k,v in dic.items():
        next[k] = int(v)
        ans += v-1
    print(ans)
    RES = defaultdict(int)
    for idx in range(n):
        value = int(S[idx])
        if RES[value] == 0:
            print("%04d"%(value))
            RES[value] = 1
            dic[value] -= 1
            next[value] = value
        elif dic[S[idx]] >= 1:
            # print('raw',raw_number)2
            raw_number = next[value]
            for i in range(1,3):
                dived = raw_number // (10 ** i)
                MOD = dived % 10
                raw_number -= (10 ** i) * MOD
                for j in range(10):
                    raw_number += ((MOD + j + 1) % 10) * max(1,(10 ** i))
                    #print(raw_number,MOD,j,i)
                    if RES[raw_number] == 0 and dic[str(raw_number)] == 0:
                        print("%04d"%(raw_number))
                        RES[raw_number] = 1
                        next[value] = raw_number
                        dic[S[idx]]-= 1
                        break
                    raw_number -= ((MOD + j + 1) % 10) * max(1,(10 ** i))
                else:
                    continue
                break

```


1328_A. Divisibility Problem

You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases.

Input

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

The only line of the test case contains two integers a and b (1 ≤ a, b ≤ 10^9).

Output

For each test case print the answer — the minimum number of moves you need to do in order to make a divisible by b.

Example

Input

5
10 4
13 9
100 13
123 456
92 46

Output

2
5
4
333
0

```python
t=int(input())
for i in range(0,t):
    a,b=input().split()
    a=int(a)
    b=int(b)
    print((b-a%b)%b)
```


1348_A. Phoenix and Balance

Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.

He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weights in the second pile. Help Phoenix minimize |a-b|, the absolute value of a-b.

Input

The input consists of multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100) — the number of test cases.

The first line of each test case contains an integer n (2 ≤ n ≤ 30; n is even) — the number of coins that Phoenix has.

Output

For each test case, output one integer — the minimum possible difference of weights between the two piles.

Example

Input

2
2
4

Output

2
6

Note

In the first test case, Phoenix has two coins with weights 2 and 4. No matter how he divides the coins, the difference will be 4-2=2.

In the second test case, Phoenix has four coins of weight 2, 4, 8, and 16. It is optimal for Phoenix to place coins with weights 2 and 16 in one pile, and coins with weights 4 and 8 in another pile. The difference is (2+16)-(4+8)=6.

```python
t=eval(input())
for j in range(t):
    n=eval(input())
    if n==2 :
        print(2)
    else:
        sum=2
        for i in range(1,n//2):
            sum=sum+2**(i+1)
        print(sum)

```


1413_A. Finding Sasuke

Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is even.

In order to open a door, Naruto must find such n seals with integer energies b_1, b_2, ..., b_n that the following equality holds: a_{1} ⋅ b_{1} + a_{2} ⋅ b_{2} + ... + a_{n} ⋅ b_{n} = 0. All b_i must be nonzero as well as a_i are, and also must not exceed 100 by absolute value. Please find required seals for every room there.

Input

The first line contains the only integer T (1 ≤ T ≤ 1000) standing for the number of rooms in the Orochimaru's lair. The other lines contain descriptions of the doors.

Each description starts with the line containing the only even integer n (2 ≤ n ≤ 100) denoting the number of seals.

The following line contains the space separated sequence of nonzero integers a_1, a_2, ..., a_n (|a_{i}| ≤ 100, a_{i} ≠ 0) denoting the energies of seals.

Output

For each door print a space separated sequence of nonzero integers b_1, b_2, ..., b_n (|b_{i}| ≤ 100, b_{i} ≠ 0) denoting the seals that can open the door. If there are multiple valid answers, print any. It can be proven that at least one answer always exists.

Example

Input

2
2
1 100
4
1 2 3 6

Output

-100 1
1 1 1 -1

Note

For the first door Naruto can use energies [-100, 1]. The required equality does indeed hold: 1 ⋅ (-100) + 100 ⋅ 1 = 0.

For the second door Naruto can use, for example, energies [1, 1, 1, -1]. The required equality also holds: 1 ⋅ 1 + 2 ⋅ 1 + 3 ⋅ 1 + 6 ⋅ (-1) = 0.

```python
T = int(input())
a = []
b=[]

i = 0
j = 0
n = 0

for i in range(T):
    n = int(input())
    a = list(map(int, input().split()))
    b.append([])
    for j in range(int(n/2)):
        if (a[j*2] > a[j*2 + 1]):
            b[i].append(a[j*2 + 1])
            b[i].append(-a[j*2])
        elif(a[j*2 + 1] >= a[j*2]):
            b[i].append(-a[j*2+1])
            b[i].append(a[j*2])

i = 0
for i in range(T):
    print(" ".join(map(str, b[i])))

```


1455_A. Strange Functions

Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111.

Let's define another function g(x) = (x)/(f(f(x))) (x is a positive integer as well).

Your task is the following: for the given positive integer n, calculate the number of different values of g(x) among all numbers x such that 1 ≤ x ≤ n.

Input

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

Each test case consists of one line containing one integer n (1 ≤ n < 10^{100}). This integer is given without leading zeroes.

Output

For each test case, print one integer — the number of different values of the function g(x), if x can be any integer from [1, n].

Example

Input

5
4
37
998244353
1000000007
12345678901337426966631415

Output

1
2
9
10
26

Note

Explanations for the two first test cases of the example:

  1. if n = 4, then for every integer x such that 1 ≤ x ≤ n, (x)/(f(f(x))) = 1;
  2. if n = 37, then for some integers x such that 1 ≤ x ≤ n, (x)/(f(f(x))) = 1 (for example, if x = 23, f(f(x)) = 23,(x)/(f(f(x))) = 1); and for other values of x, (x)/(f(f(x))) = 10 (for example, if x = 30, f(f(x)) = 3, (x)/(f(f(x))) = 10). So, there are two different values of g(x).

```python
from sys import stdout,stdin,maxsize
from collections import defaultdict,deque
import math

t=int(stdin.readline())
for _ in range(t):
    #n=int(stdin.readline())
    #d=map(int,stdin.readline().split())
    #l=list(map(int,stdin.readline().split()))
    s=input()
    print(len(s))

```


1479_B2. Painting the Array II

The only difference between the two versions is that this version asks the minimal possible answer.

Homer likes arrays a lot. Today he is painting an array a_1, a_2, ..., a_n with two kinds of colors, white and black. A painting assignment for a_1, a_2, ..., a_n is described by an array b_1, b_2, ..., b_n that b_i indicates the color of a_i (0 for white and 1 for black).

According to a painting assignment b_1, b_2, ..., b_n, the array a is split into two new arrays a^{(0)} and a^{(1)}, where a^{(0)} is the sub-sequence of all white elements in a and a^{(1)} is the sub-sequence of all black elements in a. For example, if a = [1,2,3,4,5,6] and b = [0,1,0,1,0,0], then a^{(0)} = [1,3,5,6] and a^{(1)} = [2,4].

The number of segments in an array c_1, c_2, ..., c_k, denoted seg(c), is the number of elements if we merge all adjacent elements with the same value in c. For example, the number of segments in [1,1,2,2,3,3,3,2] is 4, because the array will become [1,2,3,2] after merging adjacent elements with the same value. Especially, the number of segments in an empty array is 0.

Homer wants to find a painting assignment b, according to which the number of segments in both a^{(0)} and a^{(1)}, i.e. seg(a^{(0)})+seg(a^{(1)}), is as small as possible. Find this number.

Input

The first line contains an integer n (1 ≤ n ≤ 10^5).

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n).

Output

Output a single integer, indicating the minimal possible total number of segments.

Examples

Input

6
1 2 3 1 2 2

Output

4

Input

7
1 2 1 2 1 2 1

Output

2

Note

In the first example, we can choose a^{(0)} = [1,1,2,2], a^{(1)} = [2,3] and seg(a^{(0)}) = seg(a^{(1)}) = 2. So the answer is 2+2 = 4.

In the second example, we can choose a^{(0)} = [1,1,1,1], a^{(1)} = [2,2,2] and seg(a^{(0)}) = seg(a^{(1)}) = 1. So the answer is 1+1 = 2.

```python
import sys
input = lambda: sys.stdin.readline().rstrip()

N = int(input())
A = [int(a) for a in input().split()]
S = set()
ans = 0
la = -1
for a in A:
    if a == la:
        continue
    elif a in S:
        S = {a, la}
    else:
        S.add(a)
        la = a
        ans += 1
print(ans)

```


1506_A. Strange Table

Polycarp found a rectangular table consisting of n rows and m columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":

  * cells are numbered starting from one;
  * cells are numbered from left to right by columns, and inside each column from top to bottom;
  * number of each cell is an integer one greater than in the previous cell.

For example, if n = 3 and m = 5, the table will be numbered as follows:

$$$ \begin{matrix} 1 & 4 & 7 & 10 & 13 \\\ 2 & 5 & 8 & 11 & 14 \\\ 3 & 6 & 9 & 12 & 15 \\\ \end{matrix} $$$

However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows":

  * cells are numbered starting from one;
  * cells are numbered from top to bottom by rows, and inside each row from left to right;
  * number of each cell is an integer one greater than the number of the previous cell.

For example, if n = 3 and m = 5, then Polycarp likes the following table numbering: $$$ \begin{matrix} 1 & 2 & 3 & 4 & 5 \\\ 6 & 7 & 8 & 9 & 10 \\\ 11 & 12 & 13 & 14 & 15 \\\ \end{matrix} $$$

Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number x?

Input

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

Each test case consists of a single line containing three integers n, m, x (1 ≤ n, m ≤ 10^6, 1 ≤ x ≤ n ⋅ m), where n and m are the number of rows and columns in the table, and x is the cell number.

Note that the numbers in some test cases do not fit into the 32-bit integer type, so you must use at least the 64-bit integer type of your programming language.

Output

For each test case, output the cell number in the numbering "by rows".

Example

Input

5
1 1 1
2 2 3
3 5 11
100 100 7312
1000000 1000000 1000000000000

Output

1
2
9
1174
1000000000000

```python

def somefunc(n, m, x):
    if n == m and n == 1:
        return x
    ans = 0
    row = 0
    if x % n == 0:
        # 2
        row = x / n
    else:
        row = x // n + 1

    col = x % n
    if col == 0:
        col = n

    ans = int(m * (col - 1))
    ans += row

    return int(ans)

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

    n, m, x = map(int, input().split())
    print(somefunc(n, m, x))

```


1529_B. Sifid and Strange Subsequences

A sequence (b_1, b_2, …, b_k) is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair (i, j) with 1 ≤ i<j ≤ k, we have |a_i-a_j|≥ MAX, where MAX is the largest element of the sequence. In particular, any sequence of length at most 1 is strange.

For example, the sequences (-2021, -1, -1, -1) and (-1, 0, 1) are strange, but (3, 0, 1) is not, because |0 - 1| < 3.

Sifid has an array a of n integers. Sifid likes everything big, so among all the strange subsequences of a, he wants to find the length of the longest one. Can you help him?

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

Input

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

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

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

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

Output

For each test case output a single integer — the length of the longest strange subsequence of a.

Example

Input

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

Output

4
5
4
1
3
4

Note

In the first test case, one of the longest strange subsequences is (a_1, a_2, a_3, a_4)

In the second test case, one of the longest strange subsequences is (a_1, a_3, a_4, a_5, a_7).

In the third test case, one of the longest strange subsequences is (a_1, a_3, a_4, a_5).

In the fourth test case, one of the longest strange subsequences is (a_2).

In the fifth test case, one of the longest strange subsequences is (a_1, a_2, a_4).

```python
"""
    Author : Ashish Sasmal
    Python3 / PyPy3
"""

from sys import stdin as sin
def aint():return int(input())
def amap():return map(int,sin.readline().split())
def alist():return list(map(int,sin.readline().split()))
def astr():return input()

for _ in range(aint()):
    n = aint()
    l = alist()
    l.sort()
    m = float("inf")
    ans = 1
    for i in range(n-1):
        if l[i]<=0 and l[i+1]<=0:
            ans+=1
            m = min(m,abs(l[i+1]-l[i]))
        elif l[i]<=0 and l[i+1]>0 and l[i+1]<=m:
            ans+=1
            m = min(m,abs(l[i+1]-l[i]))
        else:
            break
    print(ans)

```


160_B. Unlucky Ticket

Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half.

But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half.

For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2 > 1 and 4 > 2), ticket 0135 also meets the criterion (the sought correspondence is 0 < 3 and 1 < 5), and ticket 3754 does not meet the criterion.

You have a ticket in your hands, it contains 2n digits. Your task is to check whether it meets the unluckiness criterion.

Input

The first line contains an integer n (1 ≤ n ≤ 100). The second line contains a string that consists of 2n digits and defines your ticket.

Output

In the first line print "YES" if the ticket meets the unluckiness criterion. Otherwise, print "NO" (without the quotes).

Examples

Input

2
2421

Output

YES

Input

2
0135

Output

YES

Input

2
3754

Output

NO

```python
number_of_testcases = 1 #int(input())

for _ in range(number_of_testcases):
    number_of_digits = int(input())
    ticket_number = input()
    ticket_number = list(ticket_number)
    first_half = ticket_number[:number_of_digits]
    second_half = ticket_number[number_of_digits:]
    #print(first_half)
    first_half.sort()
    second_half.sort()
    flag = 1
    if first_half[0] > second_half[0]:
        for i in range(number_of_digits):
            if first_half[i] <= second_half[i]:
                flag = 0
                #print("NO")

    else:
        for i in range(number_of_digits):
            if first_half[i] >= second_half[i]:
                flag = 0
                #print("NO")

    if flag==1:
        print("YES")

    else:
        print("NO")

```


227_D. Naughty Stone Piles

There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.

During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.

Your task is to determine the minimum cost at which you can gather all stones in one pile.

To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile).

Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal.

Your task is to find the minimum cost for each of q variants.

Input

The first line contains integer n (1 ≤ n ≤ 105) — the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial sizes of the stone piles.

The third line contains integer q (1 ≤ q ≤ 105) — the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≤ ki ≤ 105) — the values of number k for distinct queries. Note that numbers ki can repeat.

Output

Print q whitespace-separated integers — the answers to the queries in the order, in which the queries are given in the input.

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

Examples

Input

5
2 3 4 1 1
2
2 3

Output

9 8

Note

In the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5).

In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).

```python
n = int(input())
stones = list(map(lambda t : int(t), input().split()))
q = int(input())
queries = list(map(lambda t : int(t), input().split()))

stones.sort()

added_stones = []
added_stones.append(stones[0])
for i in range(1, n, 1):
    added_stones.append(stones[i] + added_stones[i - 1])

computed_queries = {}

for qidx, qq in enumerate(queries):
    if qq in computed_queries:
        queries[qidx] = computed_queries[qq]
        continue

    i = n - 2
    multiplier = 1
    cost = 0
    while i >= 0:
        pp = pow(qq, multiplier)
        nexti = i - pp
        if nexti < 0:
            cost += added_stones[i] * multiplier
            break
        cost += (added_stones[i] - added_stones[nexti]) * multiplier
        multiplier += 1
        i = nexti
    queries[qidx] = cost
    computed_queries[qq] = cost

print(*queries, sep=' ')
```


251_B. Playing with Permutations

Little Petya likes permutations a lot. Recently his mom has presented him permutation q1, q2, ..., qn of length n.

A permutation a of length n is a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ n), all integers there are distinct.

There is only one thing Petya likes more than permutations: playing with little Masha. As it turns out, Masha also has a permutation of length n. Petya decided to get the same permutation, whatever the cost may be. For that, he devised a game with the following rules:

  * Before the beginning of the game Petya writes permutation 1, 2, ..., n on the blackboard. After that Petya makes exactly k moves, which are described below.
  * During a move Petya tosses a coin. If the coin shows heads, he performs point 1, if the coin shows tails, he performs point 2.
    1. Let's assume that the board contains permutation p1, p2, ..., pn at the given moment. Then Petya removes the written permutation p from the board and writes another one instead: pq1, pq2, ..., pqn. In other words, Petya applies permutation q (which he has got from his mother) to permutation p.
    2. All actions are similar to point 1, except that Petya writes permutation t on the board, such that: tqi = pi for all i from 1 to n. In other words, Petya applies a permutation that is inverse to q to permutation p.

We know that after the k-th move the board contained Masha's permutation s1, s2, ..., sn. Besides, we know that throughout the game process Masha's permutation never occurred on the board before the k-th move. Note that the game has exactly k moves, that is, throughout the game the coin was tossed exactly k times.

Your task is to determine whether the described situation is possible or else state that Petya was mistaken somewhere. See samples and notes to them for a better understanding.

Input

The first line contains two integers n and k (1 ≤ n, k ≤ 100). The second line contains n space-separated integers q1, q2, ..., qn (1 ≤ qi ≤ n) — the permutation that Petya's got as a present. The third line contains Masha's permutation s, in the similar format.

It is guaranteed that the given sequences q and s are correct permutations.

Output

If the situation that is described in the statement is possible, print "YES" (without the quotes), otherwise print "NO" (without the quotes).

Examples

Input

4 1
2 3 4 1
1 2 3 4

Output

NO

Input

4 1
4 3 1 2
3 4 2 1

Output

YES

Input

4 3
4 3 1 2
3 4 2 1

Output

YES

Input

4 2
4 3 1 2
2 1 4 3

Output

YES

Input

4 1
4 3 1 2
2 1 4 3

Output

NO

Note

In the first sample Masha's permutation coincides with the permutation that was written on the board before the beginning of the game. Consequently, that violates the condition that Masha's permutation never occurred on the board before k moves were performed.

In the second sample the described situation is possible, in case if after we toss a coin, we get tails.

In the third sample the possible coin tossing sequence is: heads-tails-tails.

In the fourth sample the possible coin tossing sequence is: heads-heads.

```python
n,k=map(int,input().strip().split())
a=list(map(int,input().strip().split()))
b=list(map(int,input().strip().split()))
ups = [[i+1 for i in range(n)]]
downs = [[i+1 for i in range(n)]]

def apply(arr):
    out = [0]*n
    for i in range(n):
        out[i] = arr[a[i]-1]
    return out

def unapply(arr):
    out = [0]*n
    for i in range(n):
        out[a[i]-1] = arr[i]
    return out

for i in range(k):
    ups.append(apply(ups[i]))
for i in range(k):
    downs.append(unapply(downs[i]))

earliest = [None, None]
earliestPossible = [None, None]
for i in range(k,-1,-1):
    if ups[i] == b:
        earliest[0] = i
    if downs[i] == b:
        earliest[1] = i
        # print("YES")
        # exit(0)
for i in range(k,-1,-2):
    if ups[i] == b:
        earliestPossible[0] = i
    if downs[i] == b:
        earliestPossible[1] = i
if (not earliestPossible[0]) and (not earliestPossible[1]):
    print("NO")
    exit(0)
if ((not earliestPossible[0]) or earliest[0] < earliestPossible[0]) and ((not earliestPossible[1]) or earliest[1] < earliestPossible[1]):
    print("NO")
    exit(0)
if ups[0] == b or (ups[1] == b and downs[1] == b and k > 1):
    print("NO")
    exit(0)
print("YES")

# tem = [i+1 for i in range(n)]
# for i in range(k):
#     tem = apply(tem)
# for i in range(k):
#     tem = unapply(tem)
# print(tem)
```


276_C. Little Girl and Maximum Sum

The little girl loves the problems on array queries very much.

One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 ≤ l_i ≤ r_i ≤ n). You need to find for each query the sum of elements of the array with indexes from l_i to r_i, inclusive.

The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

Input

The first line contains two space-separated integers n (1 ≤ n ≤ 2⋅10^5) and q (1 ≤ q ≤ 2⋅10^5) — the number of elements in the array and the number of queries, correspondingly.

The next line contains n space-separated integers a_i (1 ≤ a_i ≤ 2⋅10^5) — the array elements.

Each of the following q lines contains two space-separated integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) — the i-th query.

Output

In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered.

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

Examples

Input

3 3
5 3 2
1 2
2 3
1 3

Output

25

Input

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

Output

33

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

for i in range(2, n+2):
	l[i] += l[i-1]

l.sort(reverse=True)
a.sort(reverse=True)
# print(l, a)
ans=0
for i in range(n):
	ans += l[i]*a[i]

print(ans)

```


322_C. Ciel and Robot

Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all:

  * 'U': go up, (x, y)  →  (x, y+1);
  * 'D': go down, (x, y)  →  (x, y-1);
  * 'L': go left, (x, y)  →  (x-1, y);
  * 'R': go right, (x, y)  →  (x+1, y).

The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b).

Input

The first line contains two integers a and b, ( - 109 ≤ a, b ≤ 109). The second line contains a string s (1 ≤ |s| ≤ 100, s only contains characters 'U', 'D', 'L', 'R') — the command.

Output

Print "Yes" if the robot will be located at (a, b), and "No" otherwise.

Examples

Input

2 2
RU

Output

Yes

Input

1 2
RU

Output

No

Input

-1 1000000000
LRRLU

Output

Yes

Input

0 0
D

Output

Yes

Note

In the first and second test case, command string is "RU", so the robot will go right, then go up, then right, and then up and so on.

The locations of its moves are (0, 0)  →  (1, 0)  →  (1, 1)  →  (2, 1)  →  (2, 2)  →  ...

So it can reach (2, 2) but not (1, 2).

```python
target = tuple(map(int, input().split()))
s = input()

#print(target)
#print(s)

ok = False
pos = (0, 0)
for c in s:
    if c == 'L': pos = (pos[0]-1, pos[1])
    if c == 'R': pos = (pos[0]+1, pos[1])
    if c == 'U': pos = (pos[0], pos[1]+1)
    if c == 'D': pos = (pos[0], pos[1]-1)
    if pos == target: ok = True

if pos == (0, 0):           #termin pe pozitia din care am pornit
    if ok: print('Yes')
    else: print('No')
    exit()

if pos[0] == 0:
    if target[1] * pos[1] < 0: raport = 0
    else: raport = target[1] // pos[1]
else:
    if target[0] * pos[0] < 0: raport = 0
    else: raport = target[0] // pos[0]

if raport > 0: raport = max(0, raport - 1000)
if raport < 0: raport = min(0, raport + 1000)

#print('Ajung in (%i, %i) dupa o executie, si raport = %i' %(pos[0], pos[1], raport))

coord = (pos[0] * raport, pos[1]*raport)
for rep in range(0, 10**4):
    if coord == target: ok = True
    for c in s:
        if c == 'L': coord = (coord[0]-1, coord[1])
        if c == 'R': coord = (coord[0]+1, coord[1])
        if c == 'U': coord = (coord[0], coord[1]+1)
        if c == 'D': coord = (coord[0], coord[1]-1)
        if coord == target: ok = True

if ok: print('Yes')
else: print('No')

```


347_A. Difference Row

You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.

More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn).

Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value.

Input

The first line of the input contains integer n (2 ≤ n ≤ 100). The second line contains n space-separated integers a1, a2, ..., an (|ai| ≤ 1000).

Output

Print the required sequence x1, x2, ..., xn. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value.

Examples

Input

5
100 -100 50 0 -50

Output

100 -50 0 50 -100

Note

In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.

Sequence x1, x2, ... , xp is lexicographically smaller than sequence y1, y2, ... , yp if there exists an integer r (0 ≤ r < p) such that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1.

```python
# t=int(input())
# import math
# for _ in range(t):
#     n,k=list(map(int,input().split()))
#     s=input()
#     a=[]
#     summer=0
#     for i in range(len(s)):
#         if(s[i]=='1'):
#             a.append(i)
#     i=0
#     while(i<len(a)-1):
#         dist=a[i+1]-k-1-(a[i]+k+1)+1
#         # print(a,dist)
#         if(dist>0):
#             # summer+=(dist//k)
#             summer+=(math.ceil(dist/(k+1)))
#         i+=1
#     if(len(a)>0):
#         dist=a[0]-k
#         if(dist>0):
#             summer+=(math.ceil(dist/(k+1)))

#         dist=n-1-a[-1]-k
#         if(dist>0):
#             summer+=(math.ceil(dist/(k+1)))
#     else:
#         summer+=(math.ceil(n/(k+1)))

#     print(summer)
n=int(input())
s=list(map(int,input().split()))
s.sort()
print(s[n-1],end=" ")
for a in s[1:-1]:
    print(a,end =" ")
print(s[0])
```


370_B. Berland Bingo

Lately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers.

During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.

You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.

Input

The first line of the input contains integer n (1 ≤ n ≤ 100) — the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer mi (1 ≤ mi ≤ 100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers ai, 1, ai, 2, ..., ai, mi (1 ≤ ai, k ≤ 100) — the numbers on the i-th player's card. The numbers in the lines are separated by single spaces.

It is guaranteed that all the numbers on each card are distinct.

Output

Print n lines, the i-th line must contain word "YES" (without the quotes), if the i-th player can win, and "NO" (without the quotes) otherwise.

Examples

Input

3
1 1
3 2 4 1
2 10 11

Output

YES
NO
YES

Input

2
1 1
1 1

Output

NO
NO

```python
n = int(input())
cards = [None] + [[] for i in range(n)]
for i in range(1, n+1):
    cards[i] = list(map(int, input().split()))[1:]
ans = [None] + [True for i in range(n)]
#print(cards, ans)
for i in range(1, n + 1):
    for j in range( 1, n + 1):
        if i == j :
            continue;
        if  set(cards[i]) & set(cards[j]) == set(cards[j]):
            ans[i] = False
o = ''
for i in range(1, len(ans)):
    if ans[i] == True:
        o += 'YES\n'
    elif ans[i] == False:
        o += 'NO\n'
print(o)

```


441_C. Valera and Tubes

Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).

Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that:

  * r ≥ 2;
  * for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds;
  * each table cell, which belongs to the tube, must occur exactly once in the sequence.

Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:

  * no pair of tubes has common cells;
  * each cell of the table belongs to some tube.

Help Valera to arrange k tubes on his rectangle table in a fancy manner.

Input

The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.

Output

Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells).

If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.

Examples

Input

3 3 3

Output

3 1 1 1 2 1 3
3 2 1 2 2 2 3
3 3 1 3 2 3 3

Input

2 3 1

Output

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

Note

Picture for the first sample:

<image>

Picture for the second sample:

<image>

```python

import sys
import math as mt
#input=sys.stdin.buffer.readline
#import bisect
mod=1000000007
#t=int(input())
#tot=0
t=1

for __ in range(t):
    #n=int(input())
    n,m,k=map(int,input().split())
    x,y=1,0
    d=0
    r=1
    ch=1
    cnt1=1
    for i in range(k-1):
        print(2,end=" ")
        for j in range(2):
            if y+1<=m and mt.ceil(cnt1/m)%2!=0 and ch==1:
                y+=1
                if y==m:
                    ch=0
                print(x,y,end=" ")
            elif ch==0:
                x+=1
                ch=1
                print(x,y,end=" ")
            else:
                y-=1
                if y==1:
                    ch=0
                print(x,y,end=" ")
            cnt1+=1

        print()

    if n*m-2*(k-1)>0:
        print(n*m-2*(k-1),end=" ")
        cnt=n*m-2*(k-1)
        while cnt>0:
            if y+1<=m and mt.ceil(cnt1/m)%2!=0 and ch==1:
                y+=1
                if y==m:
                    ch=0
                print(x,y,end=" ")
            elif  ch==0:
                ch=1
                x+=1
                print(x,y,end=" ")
            else:
                y-=1
                if y==1:

                    #print(x,y,ch)
                    ch=0
                print(x,y,end=" ")
            cnt-=1
            cnt1+=1

```


463_D. Gargari and Permutations

Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?

You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

Input

The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation.

Output

Print the length of the longest common subsequence.

Examples

Input

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

Output

3

Note

The answer for the first test sample is subsequence [1, 2, 3].

```python
n, k = map(int, input().split())
ra = [[0] * k for _ in range(n)]
for p in range(k):
    for i, v in enumerate(map(int, input().split())):
        v -= 1
        ra[v][p] = i
g = [[] for _ in range(n)]
for u in range(n):
    for v in range(n):
        if all(x < y for x, y in zip(ra[u], ra[v])):
            g[u].append(v)

memo = [-1] * n
def dfs(v):
    if memo[v] != -1:
        return memo[v]
    r = 1
    for u in g[v]:
        r = max(r, dfs(u) + 1)
    memo[v] = r
    return r

print(max(dfs(s) for s in range(n)))

```


487_C. Prefix Product Sequence

Consider a sequence [a1, a2, ... , an]. Define its prefix product sequence <image>.

Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].

Input

The only input line contains an integer n (1 ≤ n ≤ 105).

Output

In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists.

If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n.

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

Examples

Input

7

Output

YES
1
4
3
6
5
2
7

Input

6

Output

NO

Note

For the second sample, there are no valid sequences.

```python
n = int(input())
if n == 1:
    print('YES\n1')
    exit(0)
if n == 4:
    print('YES\n1 3 2 4')
    exit(0)
for p in range(2, int(n ** 0.5) + 1):
    if n % p == 0:
        print('NO')
        exit(0)
print('YES')
print(1)
for j in range(2, n):
    print(j * pow(j - 1, n - 2, n) % n)
print(n)
```


510_B. Fox And Two Dots

Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:

<image>

Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.

The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:

  1. These k dots are different: if i ≠ j then di is different from dj.
  2. k is at least 4.
  3. All dots belong to the same color.
  4. For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.

Determine if there exists a cycle on the field.

Input

The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board.

Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.

Output

Output "Yes" if there exists a cycle, and "No" otherwise.

Examples

Input

3 4
AAAA
ABCA
AAAA

Output

Yes

Input

3 4
AAAA
ABCA
AADA

Output

No

Input

4 4
YYYR
BYBY
BBBY
BBBY

Output

Yes

Input

7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB

Output

Yes

Input

2 13
ABCDEFGHIJKLM
NOPQRSTUVWXYZ

Output

No

Note

In first sample test all 'A' form a cycle.

In second sample there is no such cycle.

The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).

```python
'''
Zijian He
1429876
'''
# Import
from sys import setrecursionlimit
setrecursionlimit(10**6)

# Function from class
class Graph:
    def __init__ (self):
        self._alist = {}

    def add_vertex (self, vertex):
        if vertex not in self._alist:
            self._alist[vertex] = set()

    def add_edge (self, source, destination):
        self.add_vertex(source)
        self.add_vertex(destination)
        self._alist[source].add(destination)

    def is_edge (self, source, destination):
        return (self.is_vertex(source)
                and destination in self._alist[source])

    def is_vertex (self, vertex):
        return vertex in self._alist

    def neighbours (self, vertex):
        return self._alist[vertex]

    def vertices (self):
        return self._alist.keys()

class UndirectedGraph (Graph):
    def add_edge (self, a, b):
        super().add_edge (a, b)
        super().add_edge (b, a)

def depth_first_search(g, v):
    reached = {}
    def do_dfs(curr, prev):
        if curr in reached:
            return
        reached[curr] = prev
        for succ in g.neighbours(curr):
            do_dfs(succ, curr)
    do_dfs(v, v)
    return reached
#-----------------------------------------------------------------------

# Declaire the variables for checking the cycle
Detect = False

vertex = {}

def dfs_v2(g, curr, prev):
	global Detect
	global vertex

	if Detect:
		return

	vertex[curr] = True

	for succ in g.neighbours(curr):

		if vertex[succ] and succ != prev:
			Detect = True
			return
		if not vertex[succ]:
			dfs_v2(g, succ, curr)

def cycle(g):
	global Detect
	global vertex

	# Initialize all the node as unmarked
	for i in g.vertices():
		vertex[i] = False

	# Check throughout the node
	for j in g.vertices():
		if not vertex[j]:
			dfs_v2(g, j, j)
		if Detect:
			break
	return

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

# Process the input
row, col = map(int, input().split(" "))
rows = []

for i in range(row):
	rows.append(input())

# Set node as a dictionary
node = {}

for i in range(row):
	for j in range(col):
		node[i * col + j] = rows[i][j]

# Set up the graph
result_Graph = UndirectedGraph()

# Connecting the node with same color
for i in range(row * col):

	result_Graph.add_vertex(i)

	try:
		if node[i] == node[i + 1] and (i % col) != (col - 1):
			result_Graph.add_edge(i, i + 1)

		if node[i] == node[i + col]:
			result_Graph.add_edge(i, i + col)
	except:
		continue

# Main function
cycle(result_Graph)

if Detect:
	print("Yes")

else:
	print("No")

```


535_C. Tavas and Karafs

Karafs is some kind of vegetable in shape of an 1 × h rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs.

<image>

Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is si = A + (i - 1) × B.

For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.

Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that l ≤ r and sequence sl, sl + 1, ..., sr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.

Input

The first line of input contains three integers A, B and n (1 ≤ A, B ≤ 106, 1 ≤ n ≤ 105).

Next n lines contain information about queries. i-th line contains integers l, t, m (1 ≤ l, t, m ≤ 106) for i-th query.

Output

For each query, print its answer in a single line.

Examples

Input

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

Output

4
-1
8
-1

Input

1 5 2
1 5 10
2 7 4

Output

1
2

```python
a,b,n=map(int,input().split())
for _ in range(n):
    l,t,m=map(int,input().split())
    lo=l
    hi=100000000
    while lo<hi:
        mid=(lo+hi)//2
        count=(mid-l)+1
        first=a+(l-1)*b
        last=a+(mid-1)*b
        if last<=t and (count*(first+last))//2<=m*t:
            lo=mid+1
        else:
            hi=mid
    if mid!=lo:
        print(mid)
    else:
        count=(mid-1-l)+1
        first=a+(l-1)*b
        last=a+(mid-1-1)*b
        if last<=t and (count*(first+last))//2<=m*t and mid-1>=l:
            print(mid-1)
        else:
            print(-1)
```


586_A. Alena's Schedule

Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.

One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).

The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).

The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not.

Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.

Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.

Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.

Input

The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of lessons at the university.

The second line contains n numbers ai (0 ≤ ai ≤ 1). Number ai equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a1, a2, ..., an are separated by spaces.

Output

Print a single number — the number of pairs during which Alena stays at the university.

Examples

Input

5
0 1 0 1 1

Output

4

Input

7
1 0 1 0 0 1 0

Output

4

Input

1
0

Output

0

Note

In the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair.

In the last sample Alena doesn't have a single pair, so she spends all the time at home.

```python
n = int(input())
a = list(map(int, input().split())) + [0]
home = True
ans = 0
for i in range(n):
    if a[i]:
        ans += 1
        home = False
    elif not a[i + 1] and not home:
        home = True
    elif not home:
        ans += 1
print(ans)
```


608_B. Hamming Distance Sum

Genos needs your help. He was asked to solve the following programming problem by Saitama:

The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as <image>, where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.

Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.

Input

The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000).

The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000).

Both strings are guaranteed to consist of characters '0' and '1' only.

Output

Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.

Examples

Input

01
00111

Output

3

Input

0011
0110

Output

2

Note

For the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.

The second sample case is described in the statement.

```python
from sys import  stdin
input=stdin.readline
'''
if i+k
'''
def getcnt(a):
    cnt=[[0,0] for i in range(len(a)+1)]
    for i in range(len(a)):
        # if i==0:
        #     cnt[i][a[i]]+=1
        # else:
        cnt[i+1][0]=cnt[i][0]
        cnt[i+1][1]=cnt[i][1]
        cnt[i+1][a[i]]+=1
    return cnt
def f(a,b):
    ans=0
    a=list(map(int,list(a)))
    b=list(map(int,list(b)))
    lb=len(b)
    la=len(a)
    cnt=getcnt(a)
    ans=0
    for i in range(len(b)):
        lo=max(0,i-(lb-la))
        hi=min(i+1,la)
        # print(lo,hi)
        # if lo==0:
        #     lr=[0,0]
        # else:
        lr=cnt[lo]
        rr=cnt[hi]
        t=list(map(lambda x,y:x-y,rr,lr))
        ans+=t[b[i]^1]

    return ans

s=input().strip()
t=input().strip()
print(f(s,t))
```


62_A. A Student's Dream

Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.

A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych.

The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams.

So the professor began: "Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has al fingers on her left hand and ar fingers on the right one. The boy correspondingly has bl and br fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. And in addition, no three fingers of the boy should touch each other. Determine if they can hold hands so that the both were comfortable."

The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.

Input

The first line contains two positive integers not exceeding 100. They are the number of fingers on the Venusian girl's left and right hand correspondingly. The second line contains two integers not exceeding 100. They are the number of fingers on the Marsian boy's left and right hands correspondingly.

Output

Print YES or NO, that is, the answer to Petr Palych's question.

Examples

Input

5 1
10 5

Output

YES

Input

4 5
3 3

Output

YES

Input

1 2
11 6

Output

NO

Note

The boy and the girl don't really care who goes to the left.

```python
g_l,g_r=input().split()
b_l,b_r=input().split()
g_l=int(g_l)
g_r=int(g_r)
b_l=int(b_l)
b_r=int(b_r)
flag=0
if g_l==b_r:
    flag=1
elif g_l>b_r and g_l-1==b_r:
    flag=1
elif b_r>g_l and 2*g_l+2>=b_r:
    flag=1

if flag==0:
    if g_r == b_l:
        flag = 1
    elif g_r > b_l and g_r - 1 == b_l:
        flag = 1
    elif b_l > g_r and 2 * g_r + 2 >= b_l:
        flag = 1
if flag==0:
    print("NO")
else:
    print("YES")
```


724_A. Checking the Calendar

You are given names of two days of the week.

Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year.

In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.

Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".

Input

The input consists of two lines, each of them containing the name of exactly one day of the week. It's guaranteed that each string in the input is from the set "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".

Output

Print "YES" (without quotes) if such situation is possible during some non-leap year. Otherwise, print "NO" (without quotes).

Examples

Input

monday
tuesday

Output

NO

Input

sunday
sunday

Output

YES

Input

saturday
tuesday

Output

YES

Note

In the second sample, one can consider February 1 and March 1 of year 2015. Both these days were Sundays.

In the third sample, one can consider July 1 and August 1 of year 2017. First of these two days is Saturday, while the second one is Tuesday.

```python
a = str(input())
b = str(input())

k = {'monday':1,'tuesday':2,'wednesday':3,'thursday':4,'friday':5,'saturday':6,'sunday':7}

a=k[a]-1
b=k[b]-1

res = False
res = res or ((a+2)%7+1)%7==b
res = res or ((a+1)%7+1)%7==b
res = res or ((a+6)%7+1)%7==b
if res:
    print("YES")
else:
    print("NO")

```


746_A. Compote

Nikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.

Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0.

Input

The first line contains the positive integer a (1 ≤ a ≤ 1000) — the number of lemons Nikolay has.

The second line contains the positive integer b (1 ≤ b ≤ 1000) — the number of apples Nikolay has.

The third line contains the positive integer c (1 ≤ c ≤ 1000) — the number of pears Nikolay has.

Output

Print the maximum total number of lemons, apples and pears from which Nikolay can cook the compote.

Examples

Input

2
5
7

Output

7

Input

4
7
13

Output

21

Input

2
3
2

Output

0

Note

In the first example Nikolay can use 1 lemon, 2 apples and 4 pears, so the answer is 1 + 2 + 4 = 7.

In the second example Nikolay can use 3 lemons, 6 apples and 12 pears, so the answer is 3 + 6 + 12 = 21.

In the third example Nikolay don't have enough pears to cook any compote, so the answer is 0.

```python
l = int(input())
a = int(input())
p = int(input())
ll = l
aa = a // 2
pp = p // 4
print(min(ll,aa,pp) * 1 + min(ll,aa,pp) * 2 + min(ll,aa,pp) * 4)

```


769_A. Year of University Entrance

There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university.

Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than x from the year of university entrance of this student, where x — some non-negative integer. A value x is not given, but it can be uniquely determined from the available data. Note that students don't join other groups.

You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance.

Input

The first line contains the positive odd integer n (1 ≤ n ≤ 5) — the number of groups which Igor joined.

The next line contains n distinct integers a1, a2, ..., an (2010 ≤ ai ≤ 2100) — years of student's university entrance for each group in which Igor is the member.

It is guaranteed that the input data is correct and the answer always exists. Groups are given randomly.

Output

Print the year of Igor's university entrance.

Examples

Input

3
2014 2016 2015

Output

2015

Input

1
2050

Output

2050

Note

In the first test the value x = 1. Igor entered the university in 2015. So he joined groups members of which are students who entered the university in 2014, 2015 and 2016.

In the second test the value x = 0. Igor entered only the group which corresponds to the year of his university entrance.

```python
n = int(input())
a = list(map(int, input().split()))
a.sort()
if n % 2:
    print(a[n//2])
```


793_A. Oleg and shares

Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?

Input

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.

Output

Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.

Examples

Input

3 3
12 9 15

Output

3

Input

2 2
10 9

Output

-1

Input

4 1
1 1000000000 1000000000 1000000000

Output

2999999997

Note

Consider the first example.

Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.

There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.

In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.

In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.

```python
n,k=map(int,input().split())
l=list(map(int,input().split()))
K=min(l)
for i in range(n):
    if (l[i]-K)%k!=0:
        print(-1)
        exit()
Sum=sum(l)
K=K*n
Sum=Sum-K
print(Sum//k)
```


813_D. Two Melodies

Alice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time!

Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.

Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7.

You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.

Input

The first line contains one integer number n (2 ≤ n ≤ 5000).

The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — notes written on a sheet.

Output

Print maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.

Examples

Input

4
1 2 4 5

Output

4

Input

6
62 22 60 61 48 49

Output

5

Note

In the first example subsequences [1, 2] and [4, 5] give length 4 in total.

In the second example subsequences [62, 48, 49] and [60, 61] give length 5 in total. If you choose subsequence [62, 61] in the first place then the second melody will have maximum length 2, that gives the result of 4, which is not maximal.

```python
import sys

n = int(input()) + 1
a = [0] + list(map(int, input().split()))
mod7 = [x % 7 for x in a]

dp = [[0]*n for _ in range(n)]
maxnum = [0]*(10**5+10)
ans = 0

for i in range(n):
    maxmod = [0]*7

    for j in range(n):
        maxnum[a[j]] = 0

    for j in range(i):
        maxnum[a[j]] = max(maxnum[a[j]], dp[j][i])
        maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[j][i])

    for j in range(i+1, n):
        dp[i][j] = max(
            maxnum[a[j]-1],
            maxnum[a[j]+1],
            maxmod[mod7[j]],
            dp[0][i]
        ) + 1

        maxnum[a[j]] = max(maxnum[a[j]], dp[i][j])
        maxmod[mod7[j]] = max(maxmod[mod7[j]], dp[i][j])
        ans = max(ans, dp[i][j])

print(ans)

```


839_C. Journey

There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.

Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities.

Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link <https://en.wikipedia.org/wiki/Expected_value>.

Input

The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities.

Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road.

It is guaranteed that one can reach any city from any other by the roads.

Output

Print a number — the expected length of their journey. The journey starts in the city 1.

Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.

Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if <image>.

Examples

Input

4
1 2
1 3
2 4

Output

1.500000000000000

Input

5
1 2
1 3
3 4
2 5

Output

2.000000000000000

Note

In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.

In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.

```python
from queue import *

n = int(input())
g = [[] for x in range(n)]

for i in range(n-1):
  a, b = map(int, input().split())
  a -= 1
  b -= 1
  g[a].append(b)
  g[b].append(a)

used = [0]*n

anw = 0

def solve(v, d, r):
  global anw
  q = Queue()
  q.put((v, d, r))
  while not q.empty():
    v, d, r = q.get(v)
    used[v] = True
    for u in g[v]:
      if not used[u]:
        q.put((u, d+1, r*(len(g[v])-(v!=0))))
        #print("put", u)
    #print("so at", v, "len", len(g[v]))
    if v != 0 and len(g[v]) == 1:
      #print("At ", v, "is", d, r)
      anw += d/r

solve(0, 0, 1)
print(anw)
```


908_G. New Year and Original Order

Let S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555.

Given a number X, compute <image> modulo 109 + 7.

Input

The first line of input will contain the integer X (1 ≤ X ≤ 10700).

Output

Print a single integer, the answer to the question.

Examples

Input

21

Output

195

Input

345342

Output

390548434

Note

The first few values of S are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 12. The sum of these values is 195.

```python
# Problem G

num = input()
num_list = []
for i in range(len(num)):
  num_list.append(int(num[i]))
myMod = (10 ** 9) + 7
length = len(num_list)
f = [0] * (length + 1)
t = [1] * (length + 1)
for i in range(length):
    f[i+1] = (f[i] * 10 + 1) % myMod
    t[i+1] = (t[i] * 10) % myMod
ans = 0
for i in range(1, 10):
    dp = [0] * (length + 1)
    for j in range(length):
        dp[j+1] = (dp[j] * i + (10 - i) * (dp[j] * 10 + t[j])) % myMod
    c = 0
    ctr = 0
    for k in num_list:
        z = min(i, k)
        o = k - z
        ans += o * (dp[length-1-ctr] * t[c+1] + f[c+1] * t[length-1-ctr]) % myMod
        ans += z * (dp[length-1-ctr] * t[c] + f[c] * t[length-1-ctr]) % myMod
        ans %= myMod
        c += k >= i
        ctr += 1
    ans += f[c]
    if ans >= myMod:
        ans -= myMod
print(ans)

```


930_A. Peculiar apple-tree

In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.

Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.

Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.

Input

First line of input contains single integer number n (2 ≤ n ≤ 100 000) — number of inflorescences.

Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.

Output

Single line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.

Examples

Input

3
1 1

Output

1

Input

5
1 2 2 2

Output

3

Input

18
1 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4

Output

4

Note

In first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.

In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it.

```python
from collections import  defaultdict,Counter,deque as dq
from sys import  stdin
input=stdin.readline

n=int(input())
g=defaultdict(list)
w=list(map(int,input().strip().split()))
for i in range(len(w)):
	g[w[i]-1].append(i+1)
	g[i+1].append(w[i]-1)
# print(g)
q=dq([0])
d=[-1]*(n)
d[0]=1
cnt=defaultdict(int)
cnt[1]+=1
while q:
	t=q.popleft()
	for i in g[t]:
		if d[i]==-1:
			d[i]=d[t]+1
			cnt[d[i]]+=1
			q.append(i)
ans=0
for i in cnt:
	if cnt[i]%2!=0:
		ans+=1
print(ans)

```


984_A. Game

Two players play a game.

Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate turns.

The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.

You want to know what number will be left on the board after n - 1 turns if both players make optimal moves.

Input

The first line contains one integer n (1 ≤ n ≤ 1000) — the number of numbers on the board.

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

Output

Print one number that will be left on the board.

Examples

Input

3
2 1 3

Output

2

Input

3
2 2 2

Output

2

Note

In the first sample, the first player erases 3 and the second erases 1. 2 is left on the board.

In the second sample, 2 is left on the board regardless of the actions of the players.

```python
x = int(input())
l = [int(n) for n in input().split()]
l.sort()
i = 0
while len(l) > 1:
                if i % 2 == 0:
                                l = l[0:len(l) - 1]
                else:
                                l = l[1:len(l)]
                i = i + 1
print(l[0])

```