1296_E1. String Coloring (easy version)

This is an easy version of the problem. The actual problems are different, but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.

You are given a string s consisting of n lowercase Latin letters.

You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in s).

After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.

The goal is to make the string sorted, i.e. all characters should be in alphabetical order.

Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.

Input

The first line of the input contains one integer n (1 ≤ n ≤ 200) — the length of s.

The second line of the input contains the string s consisting of exactly n lowercase Latin letters.

Output

If it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.

Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of n characters, the i-th character should be '0' if the i-th character is colored the first color and '1' otherwise).

Examples

Input

9
abacbecfd

Output

YES
001010101

Input

8
aaabbcbb

Output

YES
01011011

Input

7
abcdedc

Output

NO

Input

5
abcde

Output

YES
00000

```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# ------------------- fast io --------------------

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

indexes = [[] for i in range(26)]

for i in range(len(s)):
    indexes[ord(s[i])-97] += [i]
#print(indexes)
order = [0]*n
count = 1
for each in indexes:
    incount = False
    for k in each:
        incount=True
        order[k] = count
    if incount:
        count += 1
coloring = ['']*n
opposites = [[] for i in range(n+1)]
#print(order, opposites)
for i in range(n):
    for j in range(i+1, n):
        if order[i] > order[j]:
            #print(i, j)
            for k in range(i, j):
                opposites[j] += [i]
                opposites[i] += [j]

coloring[0] = '0'

def opp(x): return '0' if x == '1' else '1'
poss = True

for i in range(n):
    if not coloring[i]:
        coloring[i] = '0'
    for k in opposites[i]:
        #print(i, k, coloring)
        if coloring[k] == '':
            coloring[k] = opp(coloring[i])
        else:
            if coloring[k] != opp(coloring[i]):
                poss = False
                break
if poss:
    print('YES')
    print(''.join(coloring))
else:
    print('NO')

```


131_E. Yet Another Task with Queens

A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.

There are m queens on a square n × n chessboard. You know each queen's positions, the i-th queen is positioned in the square (ri, ci), where ri is the board row number (numbered from the top to the bottom from 1 to n), and ci is the board's column number (numbered from the left to the right from 1 to n). No two queens share the same position.

For each queen one can count w — the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen w is between 0 and 8, inclusive.

Print the sequence t0, t1, ..., t8, where ti is the number of queens that threaten exactly i other queens, i.e. the number of queens that their w equals i.

Input

The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 105), where n is the size of the board and m is the number of queens on the board. Then m following lines contain positions of the queens, one per line. Each line contains a pair of integers ri, ci (1 ≤ ri, ci ≤ n) — the queen's position. No two queens stand on the same square.

Output

Print the required sequence t0, t1, ..., t8, separating the numbers with spaces.

Examples

Input

8 4
4 3
4 8
6 5
1 6

Output

0 3 0 1 0 0 0 0 0

Input

10 3
1 1
1 2
1 3

Output

0 2 1 0 0 0 0 0 0

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

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

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

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

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

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

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

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

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

    def __len__(self):
        return self._len

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

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

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

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

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

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

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

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

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
n,m=list(map(int,input().split()))
f=[]
maxx=[-999999999]*n
minx=[999999999]*n
maxy=[-999999999]*n
miny=[999999999]*n
maxm=[-999999999]*(2*n-1)
minm=[999999999]*(2*n-1)
maxs=[-999999999]*(2*n-1)
mins=[999999999]*(2*n-1)
r=[0 for i in range(9)]
for i in range(m):
    y,x=list(map(int,input().split()))
    a,b,c,d=y-1,x-1,y+x-2,y-x+n-1
    f.append((a,b,c,d))
    if a>maxx[b]:maxx[b]=a
    if a<minx[b]:minx[b]=a
    if x-1>maxy[a]:maxy[a]=x-1
    if x-1<miny[a]:miny[a]=x-1
    if c>maxs[d]:maxs[d]=c
    if c<mins[d]:mins[d]=c
    if d>maxm[c]:maxm[c]=d
    if d<minm[c]:minm[c]=d
for i in f:
    k=0
    if i[0]<maxx[i[1]]:k+=1
    if i[0]>minx[i[1]]:k+=1
    if i[1]<maxy[i[0]]:k+=1
    if i[1]>miny[i[0]]:k+=1
    if i[2]<maxs[i[3]]:k+=1
    if i[2]>mins[i[3]]:k+=1
    if i[3]<maxm[i[2]]:k+=1
    if i[3]>minm[i[2]]:k+=1
    r[k]+=1
print(*r)
```


1339_B. Sorted Adjacent Differences

You have array of n numbers a_{1}, a_{2}, …, a_{n}.

Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.

Note that all numbers in a are not necessarily different. In other words, some numbers of a may be same.

You have to answer independent t test cases.

Input

The first line contains a single integer t (1 ≤ t ≤ 10^{4}) — the number of test cases.

The first line of each test case contains single integer n (3 ≤ n ≤ 10^{5}) — the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}.

The second line of each test case contains n integers a_{1}, a_{2}, …, a_{n} (-10^{9} ≤ a_{i} ≤ 10^{9}).

Output

For each test case, print the rearranged version of array a which satisfies given condition. If there are multiple valid rearrangements, print any of them.

Example

Input

2
6
5 -2 4 8 6 5
4
8 1 4 2

Output

5 5 4 6 8 -2
1 2 4 8

Note

In the first test case, after given rearrangement, |a_{1} - a_{2}| = 0 ≤ |a_{2} - a_{3}| = 1 ≤ |a_{3} - a_{4}| = 2 ≤ |a_{4} - a_{5}| = 2 ≤ |a_{5} - a_{6}| = 10. There are other possible answers like "5 4 5 6 -2 8".

In the second test case, after given rearrangement, |a_{1} - a_{2}| = 1 ≤ |a_{2} - a_{3}| = 2 ≤ |a_{3} - a_{4}| = 4. There are other possible answers like "2 4 8 1".

```python
for _ in range(int(input())):
	n = int(input())
	ls = sorted(list(map(int, input().split())))
	mid = n // 2
	if n % 2 == 0:
		mid -= 1
	i = mid - 1
	turn = True
	j = mid + 1
	ar = []
	ar.append(ls[mid])
	while i >= 0 or j < n:
		if turn and j < n:
			ar.append(ls[j])
			j += 1
		elif not turn and i >= 0:
			ar.append(ls[i])
			i -= 1
		turn = not turn
	print(*ar)

```


1360_F. Spy-string

You are given n strings a_1, a_2, …, a_n: all of them have the same length m. The strings consist of lowercase English letters.

Find any string s of length m such that each of the given n strings differs from s in at most one position. Formally, for each given string a_i, there is no more than one position j such that a_i[j] ≠ s[j].

Note that the desired string s may be equal to one of the given strings a_i, or it may differ from all the given strings.

For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.

Input

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

Each test case starts with a line containing two positive integers n (1 ≤ n ≤ 10) and m (1 ≤ m ≤ 10) — the number of strings and their length.

Then follow n strings a_i, one per line. Each of them has length m and consists of lowercase English letters.

Output

Print t answers to the test cases. Each answer (if it exists) is a string of length m consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).

Example

Input

5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c

Output

abab
-1
aaa
ab
z

Note

The first test case was explained in the statement.

In the second test case, the answer does not exist.

```python
# cook your dish here
#code
import math
import collections
from sys import stdin,stdout,setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2**20)

def strcmp(s1,s2,m):
    cnt = 0
    for i in range(m):
        if(s1[i]!=s2[i]):
            cnt+=1

    return cnt

t = int(stdin.readline())

for _ in range(t):
    #n = int(stdin.readline())

    n, m = list(map(int, stdin.readline().rstrip().split()))
    a = []
    for i in range(n):
        a.append(stdin.readline().split()[0])

    if(m==1):
        print(a[0])
        continue
    else:
        ans = -1
        if(n==2):
            l = []
            for i in range(m):
                if(a[0][i]!=a[1][i]):
                    l.append(i)
            if(len(l)>=3):
                ans = -1
            else:
                if(len(l)==1 or len(l)==0):
                    ans=a[0]
                else:
                    ans = ''
                    for i in range(m):
                        if(i==l[0]):
                            ans+=a[1][i]
                        else:
                            ans+=a[0][i]
            print(ans)
            continue
        else:
            d = [[0]*n for i in range(n)]

            for i in range(n):
                for j in range(i+1,n):
                    d[i][j] = strcmp(a[i],a[j],m)
                    d[j][i] = d[i][j]

            pos = -1
            for i in range(n):
                mx = -1
                for j in range(n):
                    mx = max(mx,d[i][j])
                if(mx<=1):
                    pos = i
                    break
                if(mx==2):
                    pos = -1
                    for j in range(n):
                        if(d[i][j]==2):
                            pos = j
                            break
                    l = []
                    for k in range(m):
                        if(a[i][k]!=a[pos][k]):
                            l.append(k)
                    ans = ''
                    for k in range(m):
                        if(k==l[0]):
                            ans+=a[pos][k]
                        else:
                            ans+=a[i][k]

                    mx = -1
                    for k in range(n):
                        mx = max(mx,strcmp(ans,a[k],m))

                    if(mx<=1):
                        a[pos] = ans
                        break
                    else:
                        pos = -1

            if(pos==-1):
                print(pos)
            else:
                print(a[pos])

```


1380_G. Circular Dungeon

You are creating a level for a video game. The level consists of n rooms placed in a circle. The rooms are numbered 1 through n. Each room contains exactly one exit: completing the j-th room allows you to go the (j+1)-th room (and completing the n-th room allows you to go the 1-st room).

You are given the description of the multiset of n chests: the i-th chest has treasure value c_i.

Each chest can be of one of two types:

  * regular chest — when a player enters a room with this chest, he grabs the treasure and proceeds to the next room;
  * mimic chest — when a player enters a room with this chest, the chest eats him alive, and he loses.

The player starts in a random room with each room having an equal probability of being chosen. The players earnings is equal to the total value of treasure chests he'd collected before he lost.

You are allowed to choose the order the chests go into the rooms. For each k from 1 to n place the chests into the rooms in such a way that:

  * each room contains exactly one chest;
  * exactly k chests are mimics;
  * the expected value of players earnings is minimum possible.

Please note that for each k the placement is chosen independently.

It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the values of P ⋅ Q^{-1} \pmod {998244353}.

Input

The first contains a single integer n (2 ≤ n ≤ 3 ⋅ 10^5) — the number of rooms and the number of chests.

The second line contains n integers c_1, c_2, ..., c_n (1 ≤ c_i ≤ 10^6) — the treasure values of each chest.

Output

Print n integers — the k -th value should be equal to the minimum possible expected value of players earnings if the chests are placed into the rooms in some order and exactly k of the chests are mimics.

It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the values of P ⋅ Q^{-1} \pmod {998244353}.

Examples

Input

2
1 2

Output

499122177 0

Input

8
10 4 3 6 5 10 7 5

Output

499122193 249561095 249561092 873463811 499122178 124780545 623902721 0

Note

In the first example the exact values of minimum expected values are: \frac 1 2, \frac 0 2.

In the second example the exact values of minimum expected values are: \frac{132} 8, \frac{54} 8, \frac{30} 8, \frac{17} 8, \frac{12} 8, \frac 7 8, \frac 3 8, \frac 0 8.

```python
import sys

sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def solve():
    cs = [aa[0]]
    for a in aa[1:]: cs.append((cs[-1] + a) % md)
    # print(cs)

    inv = pow(n, md - 2, md)
    ans = []
    for k in range(1, n):
        cur = 0
        for i in range(1, n):
            if n - 1 - k * i < 0: break
            cur = (cur + cs[n - 1 - k * i]) % md
        cur = cur * inv % md
        ans.append(cur)
    ans.append(0)
    print(*ans)

md=998244353
n=II()
aa=LI()
aa.sort()
solve()

```


1424_G. Years

During one of the space missions, humans have found an evidence of previous life at one of the planets. They were lucky enough to find a book with birth and death years of each individual that had been living at this planet. What's interesting is that these years are in the range (1, 10^9)! Therefore, the planet was named Longlifer.

In order to learn more about Longlifer's previous population, scientists need to determine the year with maximum number of individuals that were alive, as well as the number of alive individuals in that year. Your task is to help scientists solve this problem!

Input

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

Each of the following n lines contain two integers b and d (1 ≤ b < d ≤ 10^9) representing birth and death year (respectively) of each individual.

Output

Print two integer numbers separated by blank character, y — the year with a maximum number of people alive and k — the number of people alive in year y.

In the case of multiple possible solutions, print the solution with minimum year.

Examples

Input

3
1 5
2 4
5 6

Output

2 2

Input

4
3 4
4 5
4 6
8 10

Output

4 2

Note

You can assume that an individual living from b to d has been born at the beginning of b and died at the beginning of d, and therefore living for d - b years.

```python
dct = {}
for i in range(int(input())):
    a,b = map(int,input().split())
    dct[a] = dct.get(a,0)+1
    dct[b] = dct.get(b,0)-1
cnt = curr = y = 0
for i in sorted(dct.keys()):
    curr += dct[i]
    if curr > cnt :
        cnt = curr
        y = i
print(y,cnt)

```


1445_C. Division

Oleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.

To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that:

  * p_i is divisible by x_i;
  * x_i is not divisible by q_i.

Oleg is really good at division and managed to find all the answers quickly, how about you?

Input

The first line contains an integer t (1 ≤ t ≤ 50) — the number of pairs.

Each of the following t lines contains two integers p_i and q_i (1 ≤ p_i ≤ 10^{18}; 2 ≤ q_i ≤ 10^{9}) — the i-th pair of integers.

Output

Print t integers: the i-th integer is the largest x_i such that p_i is divisible by x_i, but x_i is not divisible by q_i.

One can show that there is always at least one value of x_i satisfying the divisibility conditions for the given constraints.

Example

Input

3
10 4
12 6
179 822

Output

10
4
179

Note

For the first pair, where p_1 = 10 and q_1 = 4, the answer is x_1 = 10, since it is the greatest divisor of 10 and 10 is not divisible by 4.

For the second pair, where p_2 = 12 and q_2 = 6, note that

  * 12 is not a valid x_2, since 12 is divisible by q_2 = 6;
  * 6 is not valid x_2 as well: 6 is also divisible by q_2 = 6.

The next available divisor of p_2 = 12 is 4, which is the answer, since 4 is not divisible by 6.

```python
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""

import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right

from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
    return [int(s) for s in input().split()]

def getInt():
    return int(input())

def getStrs():
    return [s for s in input().split()]

def getStr():
    return input()

def listStr():
    return list(input())

MOD = 10**9+7

"""
Start with P
P has factors pi**qi
X = P, is X % Q == 0, doesn't work

Need the largest factor of P s.t. factor % Q = 0

30
10
1 2 3 5 6 10 15 30 so 15 is the answer

If P//Q is the smallest factor of P, the answer is the next smallest factor
Otherwise, the answer is either the next factor, or a smaller factor which doesn't divide P//Q

We need to remove a combination of factors from P until it doesn't divide Q any more

50 = 2*2*5
100 = 2*2*5*5

10 = 2*5
30 = 2*3*5

Answer = 5*5

"""
from functools import reduce

def factors(n):
    return set(reduce(list.__add__,
                ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

def solve():
    P, Q = getInts()
    if P < Q:
        return P
    if P % Q > 0:
        return P
    facs = sorted(list(factors(Q)))
    best = 0
    for fac in facs:
        if fac == 1:
            continue
        power = 1
        while P % fac**power == 0:
            #print(P,fac,power,flush=True)
            tmp = P//(fac**power)
            if tmp % Q > 0:
                best = max(best,tmp)
            power += 1
    return best

for _ in range(getInt()):
    print(solve())
```


146_C. Lucky Conversion

Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types:

  * replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4);
  * swap any pair of digits in string a.

Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.

Input

The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.

Output

Print on the single line the single number — the minimum number of operations needed to convert string a into string b.

Examples

Input

47
74

Output

1

Input

774
744

Output

1

Input

777
444

Output

3

Note

In the first sample it is enough simply to swap the first and the second digit.

In the second sample we should replace the second digit with its opposite.

In the third number we should replace all three digits with their opposites.

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

da={'4':0,'7':0}
db={'4':0,'7':0}

for i in a:
    da[i]+=1
for i in b:
    db[i]+=1

dif=0
for i in range(len(a)):
    if(a[i]!=b[i]):
        dif+=1
ans=0
if(da==db):
    ans=dif//2
else:
    x=abs(da['4']-db['4'])
    ans+=x
    dif-=x
    ans+=(dif//2)

print(ans)

```


1519_B. The Cake Is a Lie

There is a n × m grid. You are standing at cell (1, 1) and your goal is to finish at cell (n, m).

You can move to the neighboring cells to the right or down. In other words, suppose you are standing at cell (x, y). You can:

  * move right to the cell (x, y + 1) — it costs x burles;
  * move down to the cell (x + 1, y) — it costs y burles.

Can you reach cell (n, m) spending exactly k burles?

Input

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

The first and only line of each test case contains three integers n, m, and k (1 ≤ n, m ≤ 100; 0 ≤ k ≤ 10^4) — the sizes of grid and the exact amount of money you need to spend.

Output

For each test case, if you can reach cell (n, m) spending exactly k burles, print YES. Otherwise, print NO.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

Example

Input

6
1 1 0
2 2 2
2 2 3
2 2 4
1 4 3
100 100 10000

Output

YES
NO
YES
NO
YES
NO

Note

In the first test case, you are already in the final cell, so you spend 0 burles.

In the second, third and fourth test cases, there are two paths from (1, 1) to (2, 2): (1, 1) → (1, 2) → (2, 2) or (1, 1) → (2, 1) → (2, 2). Both costs 1 + 2 = 3 burles, so it's the only amount of money you can spend.

In the fifth test case, there is the only way from (1, 1) to (1, 4) and it costs 1 + 1 + 1 = 3 burles.

```python
t = int(input())
while t > 0:
    n, m, k = map(int, input().split())
    if k == n * m - 1:
        print('Yes')
    else:
        print('No')
    t -= 1

```


1546_B. AquaMoon and Stolen String

AquaMoon had n strings of length m each. n is an odd number.

When AquaMoon was gone, Cirno tried to pair these n strings together. After making (n-1)/(2) pairs, she found out that there was exactly one string without the pair!

In her rage, she disrupted each pair of strings. For each pair, she selected some positions (at least 1 and at most m) and swapped the letters in the two strings of this pair at the selected positions.

For example, if m = 6 and two strings "abcdef" and "xyzklm" are in one pair and Cirno selected positions 2, 3 and 6 she will swap 'b' with 'y', 'c' with 'z' and 'f' with 'm'. The resulting strings will be "ayzdem" and "xbcklf".

Cirno then stole away the string without pair and shuffled all remaining strings in arbitrary order.

AquaMoon found the remaining n-1 strings in complete disarray. Also, she remembers the initial n strings. She wants to know which string was stolen, but she is not good at programming. Can you help her?

Input

This problem is made as interactive. It means, that your solution will read the input, given by the interactor. But the interactor will give you the full input at the beginning and after that, you should print the answer. So you should solve the problem, like as you solve the usual, non-interactive problem because you won't have any interaction process. The only thing you should not forget is to flush the output buffer, after printing the answer. Otherwise, you can get an "Idleness limit exceeded" verdict. Refer to the [interactive problems guide](https://codeforces.com/blog/entry/45307) for the detailed information about flushing the output buffer.

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

The first line of each test case contains two integers n, m (1 ≤ n ≤ 10^5, 1 ≤ m ≤ 10^5) — the number of strings and the length of each string, respectively.

The next n lines each contain a string with length m, describing the original n strings. All string consists of lowercase Latin letters.

The next n-1 lines each contain a string with length m, describing the strings after Cirno exchanged and reordered them.

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

Hack format:

The first line should contain a single integer t. After that t test cases should follow in the following format:

The first line should contain two integers n and m.

The following n lines should contain n strings of length m, describing the original strings.

The following (n-1)/(2) lines should describe the pairs. They should contain, in the following order: the index of the first string i (1 ≤ i ≤ n), the index of the second string j (1 ≤ j ≤ n, i ≠ j), the number of exchanged positions k (1 ≤ k ≤ m), and the list of k positions that are exchanged (k distinct indices from 1 to m in any order).

The final line should contain a permutation of integers from 1 to n, describing the way the strings should be reordered. The strings will be placed in the order indices placed in this permutation, the stolen string index will be ignored.

Output

For each test case print a single line with the stolen string.

Example

Input

3
3 5
aaaaa
bbbbb
ccccc
aaaaa
bbbbb
3 4
aaaa
bbbb
cccc
aabb
bbaa
5 6
abcdef
uuuuuu
kekeke
ekekek
xyzklm
xbcklf
eueueu
ayzdem
ukukuk

Output

ccccc
cccc
kekeke

Note

In the first test case, "aaaaa" and "bbbbb" exchanged all positions, and "ccccc" is the stolen string.

In the second test case, "aaaa" and "bbbb" exchanged two first positions, and "cccc" is the stolen string.

This is the first test in the hack format:

    3
    3 5
    aaaaa
    bbbbb
    ccccc
    1 2 5 1 2 3 4 5
    2 1 3
    3 4
    aaaa
    bbbb
    cccc
    1 2 2 1 2
    2 1 3
    5 6
    abcdef
    uuuuuu
    kekeke
    ekekek
    xyzklm
    1 5 3 2 3 6
    2 4 3 2 4 6
    5 4 1 2 3

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

def solve():
    n, m = map(int, input().split())
    original = [input() for _ in range(n)]
    modified = [input() for _ in range(n-1)]
    stolen_chars = []
    for j in range(m):
        chars_available = 0
        for i in range(n):
            chars_available += ord(original[i][j])
        for i in range(n-1):
            chars_available -= ord(modified[i][j])
        stolen_chars.append(chr(chars_available))
    return ''.join(stolen_chars)

t = int(input())
output = []
for _ in range(t):
    print(solve())
sys.stdout.flush()
```


266_B. Queue at the School

During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each second.

Let's describe the process more precisely. Let's say that the positions in the queue are sequentially numbered by integers from 1 to n, at that the person in the position number 1 is served first. Then, if at time x a boy stands on the i-th position and a girl stands on the (i + 1)-th position, then at time x + 1 the i-th position will have a girl and the (i + 1)-th position will have a boy. The time is given in seconds.

You've got the initial position of the children, at the initial moment of time. Determine the way the queue is going to look after t seconds.

Input

The first line contains two integers n and t (1 ≤ n, t ≤ 50), which represent the number of children in the queue and the time after which the queue will transform into the arrangement you need to find.

The next line contains string s, which represents the schoolchildren's initial arrangement. If the i-th position in the queue contains a boy, then the i-th character of string s equals "B", otherwise the i-th character equals "G".

Output

Print string a, which describes the arrangement after t seconds. If the i-th position has a boy after the needed time, then the i-th character a must equal "B", otherwise it must equal "G".

Examples

Input

5 1
BGGBG

Output

GBGGB

Input

5 2
BGGBG

Output

GGBGB

Input

4 1
GGGB

Output

GGGB

```python

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

for i in range(t):
    j = 0
    while j < n:
        while j < n and a[j] == 'G':
            j += 1
        while j < n and a[j] == 'B':
            j += 1
        if j < n:
            a[j - 1], a[j] = 'G', 'B'
            j += 1

for i in a:
    print(i, end = '')
```


28_B. pSort

One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited.

The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.

Input

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.

Output

If the given state is reachable in the described game, output YES, otherwise NO.

Examples

Input

5
5 4 3 2 1
1 1 1 1 1

Output

YES

Input

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

Output

NO

Input

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

Output

YES

```python
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[[] for i in range(n)]
for i in range(n):
    if i-b[i]>=0:
        c[i].append(i-b[i])
        c[i-b[i]].append(i)
    if i+b[i]<n:
        c[i].append(i+b[i])
        c[i+b[i]].append(i)
v=[1]*n
def dfs(u):
    global v,c
    v[u]=0
    for i in c[u]:
        if v[i]:
            dfs(i)
for i in range(n):
    v=[1]*n
    dfs(a[i]-1)
    if v[i]:
        print('NO')
        break
else:
    print('YES')
```


315_B. Sereja and Array

Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:

  1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
  2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).
  3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.

Help Sereja, complete all his operations.

Input

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array.

Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

Output

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.

Examples

Input

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

Output

2
9
11
20
30
40
39

```python
import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq

#sys.setrecursionlimit(10**7)
# OneDrive\Documents\codeforces

I=sys.stdin.readline

alpha="abcdefghijklmnopqrstuvwxyz"

mod=10**9 + 7

"""
x_move=[-1,0,1,0,-1,1,1,-1]
y_move=[0,1,0,-1,1,1,-1,-1]
"""
def ii():
	return int(I().strip())
def li():
	return list(map(int,I().strip().split()))
def mi():
	return map(int,I().strip().split())

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom

def ispali(s):
	i=0
	j=len(s)-1

	while i<j:
		if s[i]!=s[j]:
			return False
		i+=1
		j-=1
	return True

def isPrime(n):
	if n<=1:
		return False
	elif n<=2:
		return True
	else:

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

def main():
	n,m=mi()
	arr=li()
	ans=""
	cnt=0
	for i in range(m):
		op=li()
		if op[0]==1:
			arr[op[1]-1]=op[2]-cnt
		elif op[0]==2:
			cnt+=op[1]
		else:
			ans+=str(arr[op[1]-1]+cnt)+"\n"
	print(ans)

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


337_D. Book of Evil

Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.

The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.

Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.

Input

The first line contains three space-separated integers n, m and d (1 ≤ m ≤ n ≤ 100000; 0 ≤ d ≤ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 ≤ pi ≤ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.

Output

Print a single number — the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.

Examples

Input

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

Output

3

Note

Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.

<image>

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

class graph:
    def __init__(self,n,mark):
        self.d=defaultdict(list)
        self.n=n
        self.mark=mark

    def add(self,s,d):
        self.d[s].append(d)
        self.d[d].append(s)

    def bfs(self,s,dis):
        marked=s
        visited=[False]*self.n
        visited[s]=True
        q=[s]
        while q:
            s=q.pop(0)
            if(s in mark):
                marked=s
            for i in self.d[s]:
                if(visited[i]==False):
                    q.append(i)
                    visited[i]=True
                    dis[i]+=dis[s]+1
        return marked

n,m,k=map(int,input().split())
mrk=[int(x) for x in input().split()]
mark={}
for i in mrk:
    mark[i-1]=1

g=graph(n,mark)

for i in range(n-1):
    a,b=map(int,input().split())
    g.add(a-1,b-1)
dis=[0]*n
u=g.bfs(0,dis)
dis=[0]*n
d=g.bfs(u,dis)
#print(dis)
temp=[0]*n
x=g.bfs(d,temp)
#print(temp)
count=0
for i in range(n):
    if(temp[i]<=k and dis[i]<=k):
        count+=1
print(count)

```


360_A. Levko and Array Recovery

Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:

  1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li ≤ j ≤ ri.
  2. Find the maximum of elements from li to ri. That is, calculate the value <image>.

Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 5000) — the size of the array and the number of operations in Levko's records, correspondingly.

Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 ≤ ti ≤ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 ≤ li ≤ ri ≤ n,  - 104 ≤ di ≤ 104) — the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 ≤ li ≤ ri ≤ n,  - 5·107 ≤ mi ≤ 5·107) — the description of the operation of the second type.

The operations are given in the order Levko performed them on his array.

Output

In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.

If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| ≤ 109) — the recovered array.

Examples

Input

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

Output

YES
4 7 4 7

Input

4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13

Output

NO

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

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

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

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

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

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7

Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()

n,m = Ri()
lis = []
for i in range(m):
    lis.append(Ri())
ans = [10**9]*n
for i in range(m-1,-1,-1):
    if lis[i][0] == 2:
        for j in range(lis[i][1]-1,lis[i][2]):
            ans[j] = min(ans[j], lis[i][3])
    else:
        for j in range(lis[i][1]-1,lis[i][2]):
            if ans[j] != 10**9:
                ans[j]-=lis[i][3]

for i in range(n):
    if ans[i] == 10**9:
        ans[i] = -10**9
temp = ans[:]
# print(temp)
flag = True
for i in range(m):
    if lis[i][0] == 2:
        t= -10**9
        for j in range(lis[i][1]-1,lis[i][2]):
            t = max(t, temp[j])
        if t != lis[i][3]:
            flag = False
            break
    else:
        for j in range(lis[i][1]-1,lis[i][2]):
            temp[j]+=lis[i][3]
# print(temp, ans)
if flag :
    YES()
    print(*ans)
else:
    NO()
    # print(-1)
```


383_D. Antimatter

Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 ≤ i ≤ n) can create either ai units of matter or ai units of antimatter.

Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).

You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.

Input

The first line contains an integer n (1 ≤ n ≤ 1000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000).

The sum a1 + a2 + ... + an will be less than or equal to 10000.

Output

Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).

Examples

Input

4
1 1 1 1

Output

12

Note

The possible photos are [1+, 2-], [1-, 2+], [2+, 3-], [2-, 3+], [3+, 4-], [3-, 4+], [1+, 2+, 3-, 4-], [1+, 2-, 3+, 4-], [1+, 2-, 3-, 4+], [1-, 2+, 3+, 4-], [1-, 2+, 3-, 4+] and [1-, 2-, 3+, 4+], where "i+" means that the i-th element produces matter, and "i-" means that the i-th element produces antimatter.

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

sys.setrecursionlimit(2*10**5+10)
write = lambda x: sys.stdout.write(x+"\n")
debug = lambda x: sys.stderr.write(x+"\n")
writef = lambda x: print("{:.12f}".format(x))

n = int(input())
a = list(map(int, input().split()))
m = sum(a)
M = 10**9+7
dp = [0]*(2*m+1)
ans = 0
dp[m] = 1
val = 0
for i in range(n):
    v = a[i]
    ndp = [0]*(2*m+1)
    for j in range(2*m+1):
        if j-v>=0:
            ndp[j-v] += dp[j]
            if ndp[j-v]>M:
                ndp[j-v] -= M
        if j+v<=2*m:
            ndp[j+v] += dp[j]
            if ndp[j+v]>M:
                ndp[j+v] -= M
    dp = ndp
    ans += dp[m]
    ans %= M
    dp[m] += 1
    val += v
print(ans%M)
```


404_C. Restore Graph

Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.

One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.

Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.

Input

The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.

The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.

Output

If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph.

In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.

Examples

Input

3 2
0 1 1

Output

3
1 2
1 3
3 2

Input

4 2
2 0 1 3

Output

3
1 3
1 4
2 3

Input

3 1
0 0 0

Output

-1

```python
from sys import exit

n, k = map(int, input().split())
nodes = [[] for _ in range(n+1)]
edges = []

for node, dist in enumerate(map(int, input().split())):
    nodes[dist].append(node)

if len(nodes[0]) != 1 or len(nodes[1]) > k:
    print(-1)
else:
    for i in range(1, n):
        if len(nodes[i])*(k-1) < len(nodes[i+1]):
            print(-1)
            exit(0)
    for i in range(n):

        next = 0

        if len(nodes[i+1]) > 0:
            for j, node in enumerate(nodes[i]):

                current = 0

                while current < (k if i == 0 else k-1) and next < len(nodes[i+1]):
                    edges.append((node+1, nodes[i+1][next]+1))
                    next += 1
                    current += 1

    print(len(edges))
    print('\n'.join(map(lambda x: ' '.join([str(x[0]), str(x[1])]), edges)))

```


431_D. Random Task

One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly k digits one".

The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.

Input

The first line contains two space-separated integers, m and k (0 ≤ m ≤ 1018; 1 ≤ k ≤ 64).

Output

Print the required number n (1 ≤ n ≤ 1018). If there are multiple answers, print any of them.

Examples

Input

1 1

Output

1

Input

3 2

Output

5

```python
def dfs(n, k, cache = {}):
    # if number of bits is bigger than the number's bits of the number's bits is less than 0
    if k > n or k < 0: return 0
    # if num bits is 0 or num bits is equivalent to the number's bits
    if k == 0 or k == n: return 1
    # This optimization is not necessary but flips the 0s and the 1s
    # if k*2 > n: k = n-k
    # Check is already calculated
    if (n, k) in cache: return cache[(n, k)]
    # Use dfs addition for case where certain bit is 1 or certain bit is 0
    z = cache[(n, k)] = dfs(n-1, k-1) + dfs(n-1, k)
    return z

def bits(n):
    # counts number of 1s in the number
    b = 0
    while n:
        if n & 1: b += 1
        n >>= 1
    return b

def count(n, k):
    z, b, c = 0, 63, 0
    for b in reversed(range(64)):
        # Taking n and checking if certain bit is 1 or not
        # This sums for every mod power of 2 that exists to account for every case
        if (n>>b)&1:
            # calculates by subtracting for bits not accounted for
            z += dfs(b, k-c)
            c += 1
        # Unnecessary code
        # if not k: break
    # if original number has same number of 1s as digits required, add 1
    return z + (bits(n) == k)

def solve(m, k):
    # Binary Search for number 1-10^18
    low, high = 1, 10**18
    while low < high:
        mid = (low+high)//2
        if count(2*mid, k) - count(mid, k) < m:
            low = mid+1
        else:
            high = mid
    return high

m, k = [int(x) for x in input().split()]
print(solve(m, k))
```


454_A. Little Pony and Crystal Mine

Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.

You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.

Input

The only line contains an integer n (3 ≤ n ≤ 101; n is odd).

Output

Output a crystal of size n.

Examples

Input

3

Output

*D*
DDD
*D*

Input

5

Output

**D**
*DDD*
DDDDD
*DDD*
**D**

Input

7

Output

***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***

```python
n=int(input())
a=int(n/2)
b=1
for i in range(int(n/2)):
    for j in range(a):
        print("*",end="")
    for j in range(b):
        print('D',end="")
    b=b+2
    for j in range(a):
        print("*",end="")
    a=a-1
    print()
for i in range(b):
    print("D",end="")
print()
a=a+1
b=b-2
for i in range(int(n/2)):
    for j in range(a):
        print("*",end="")
    for j in range(b):
        print('D',end="")
    b=b-2
    for j in range(a):
        print("*",end="")
    a=a+1
    print()

```


476_D. Dreamoon and Sets

Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.

Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.

Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.

Input

The single line of the input contains two space separated integers n, k (1 ≤ n ≤ 10 000, 1 ≤ k ≤ 100).

Output

On the first line print a single integer — the minimal possible m.

On each of the next n lines print four space separated integers representing the i-th set.

Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.

Examples

Input

1 1

Output

5
1 2 3 5

Input

2 2

Output

22
2 4 6 22
14 18 10 16

Note

For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.

```python
n,k = [int(i) for i in input().split()]
print((6*n-1)*k)
for a in range(n):
    val = 6*a
    print((val+1)*k,(val+2)*k,(val+3)*k,(val+5)*k)

```


49_E. Common ancestor

The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are n permissible substitutions. The substitution ai->bici means that any one symbol ai can be replaced with two symbols bici. Every substitution could happen an unlimited number of times.

They say that two creatures with DNA sequences s1 and s2 can have a common ancestor if there exists such a DNA sequence s3 that throughout evolution it can result in s1 and s2, perhaps after a different number of stages. Your task is to find out by the given s1 and s2 whether the creatures possessing such DNA sequences can have a common ancestor. If the answer is positive, you have to find the length of the shortest sequence of the common ancestor’s DNA.

Input

The first line contains a non-empty DNA sequence s1, the second line contains a non-empty DNA sequence s2. The lengths of these lines do not exceed 50, the lines contain only lowercase Latin letters. The third line contains an integer n (0 ≤ n ≤ 50) — the number of permissible substitutions. Then follow n lines each of which describes a substitution in the format ai->bici. The characters ai, bi, and ci are lowercase Latin letters. Lines s1 and s2 can coincide, the list of substitutions can contain similar substitutions.

Output

If s1 and s2 cannot have a common ancestor, print -1. Otherwise print the length of the shortest sequence s3, from which s1 and s2 could have evolved.

Examples

Input

ababa
aba
2
c->ba
c->cc

Output

2

Input

ababa
aba
7
c->ba
c->cc
e->ab
z->ea
b->ba
d->dd
d->ab

Output

1

Input

ababa
aba
1
c->ba

Output

-1

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

import itertools
import collections

# Read input strings
s1 = input()
s2 = input()

# Read evolution rules, use a mapping from the 2 target characters to the source character
rules = collections.defaultdict(set)
n = int(input())
for i in range(n):
  rule = input()
  target = rule[-2:]
  source = rule[0]
  rules[target].add(source)

def substrings_of_precise_length(s, l):
  # Generator for all substrings of s that are of length l
  for start_pos in range(len(s)-l+1):
    yield s[start_pos:start_pos+l]

def substrings_of_minimum_length(s, minlen):
  # Generator for all substrings of s that are of length l or larger, in order from short to long length
  return itertools.chain.from_iterable(substrings_of_precise_length(s,l) for l in range(minlen, len(s)+1))

def partitions_of_string(s):
  # Generator for all possible pairs (a,b) such that a+b = c where a and b are not empty strings
  for l1 in range(1, len(s)):
    yield (s[:l1], s[l1:])

# Dictionary mapping strings onto the set of single characters from which those strings could evolve
ancestors = collections.defaultdict(set)

def update_ancestors(ancestors, rules, s):
  # Update the ancestor dictionary for string s
  # O(len(s)**3 * len(rules))

  # All single characters can "evolve" from a single character
  for c in s:
    ancestors[c].add(c)

  # Examine all substrings of s, in order of increasing length
  for sub in substrings_of_minimum_length(s, 2):
    # Examine any way the substring can be created from two seperate, smaller strings
    for (sub1, sub2) in partitions_of_string(sub):
      # Check all rules to see if the two substrings can evolve from a single character by using that rule
      for target, sources in rules.items():
        if (target[0] in ancestors[sub1]) and (target[1] in ancestors[sub2]):
          ancestors[sub].update(sources)

# Update the ancestors based on s1 and s2
update_ancestors(ancestors, rules, s1)
update_ancestors(ancestors, rules, s2)

def prefixes(s):
  # Generator for all non-empty prefixes of s, in order of increasing length
  for l in range(1, len(s)+1):
    yield s[:l]

def determine_shortest_common_ancestor(ancestors, s1, s2):
  # Returns the length of the shortest common ancestor of string s1 and s2, or float('inf') if there is no common ancestor.
  # The ancestors is a dictionary that contains for every substring of s1 and s2 the set of single characters from which that substring can evolve
  # O(len(s1)**2 * len(s2)**2 * 26 )

  # Dictionary mapping pairs of strings onto the length of their shortest common ancestor
  shortest_common_ancestor = collections.defaultdict(lambda:float('inf'))

  # Check every possible combinations of prefixes of s1 and s2
  for (pre1,pre2) in itertools.product(prefixes(s1), prefixes(s2)):
    # If both prefixes have an overlap in the single character from which they can evolve, then the shortest common ancestor is 1 letter
    if not ancestors[pre1].isdisjoint(ancestors[pre2]):
      shortest_common_ancestor[(pre1,pre2)] = 1

    # Check all possible combinations of partitions of pre1 and pre2
    temp = shortest_common_ancestor[(pre1, pre2)]
    for ((sub1a,sub1b),(sub2a,sub2b)) in itertools.product(partitions_of_string(pre1), partitions_of_string(pre2)):
      if not ancestors[sub1b].isdisjoint(ancestors[sub2b]):
        # sub1b and sub2b can evolve from the same character, so the shortest common ancestor of sub1a+sub1b and sub2a+sub2b is
        # never longer than the shortest common ancestor of sub1a and sub2a plus the one letter from which sub1b and sub2b can evolve
        temp = min(temp, shortest_common_ancestor[(sub1a, sub2a)] + 1)
    shortest_common_ancestor[(pre1, pre2)] = temp

  return shortest_common_ancestor[(s1, s2)]

answer = determine_shortest_common_ancestor(ancestors, s1, s2)
if (answer == float('inf')):
  print(-1)
else:
  print(answer)

```


577_A. Multiplication Table

Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1.

You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.

Input

The single line contains numbers n and x (1 ≤ n ≤ 105, 1 ≤ x ≤ 109) — the size of the table and the number that we are looking for in the table.

Output

Print a single number: the number of times x occurs in the table.

Examples

Input

10 5

Output

2

Input

6 12

Output

4

Input

5 13

Output

0

Note

A table for the second sample test is given below. The occurrences of number 12 are marked bold.

<image>

```python
import sys
n, x = map(int, sys.stdin.readline().split())
s = 0
for i in range(1, n + 1):
    if (x % i == 0 and x / i <= n):
        s += 1
print(s)

```


599_D. Spongebob and Squares

Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two and 3 squares with side three. The total number of distinct squares in a 3 × 5 table is 15 + 8 + 3 = 26.

Input

The first line of the input contains a single integer x (1 ≤ x ≤ 1018) — the number of squares inside the tables Spongebob is interested in.

Output

First print a single integer k — the number of tables with exactly x distinct squares inside.

Then print k pairs of integers describing the tables. Print the pairs in the order of increasing n, and in case of equality — in the order of increasing m.

Examples

Input

26

Output

6
1 26
2 9
3 5
5 3
9 2
26 1

Input

2

Output

2
1 2
2 1

Input

8

Output

4
1 8
2 3
3 2
8 1

Note

In a 1 × 2 table there are 2 1 × 1 squares. So, 2 distinct squares in total.

<image>

In a 2 × 3 table there are 6 1 × 1 squares and 2 2 × 2 squares. That is equal to 8 squares in total.

<image>

```python
n,i,t,r=int(input()),0,0,[]
while 1:
	i+=1
	n-=i*i
	if n<0:break
	t+=i
	m=n//t
	r+=[(m+i,i),(i,m+i)][m==0:]*(m*t==n)
print(len(r))
for p in sorted(r):print("%d %d"%p)
```


620_C. Pearls in a Row

There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.

Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.

Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

Input

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row.

The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

Output

On the first line print integer k — the maximal number of segments in a partition of the row.

Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment.

Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type.

If there are several optimal solutions print any of them. You can print the segments in any order.

If there are no correct partitions of the row print the number "-1".

Examples

Input

5
1 2 3 4 1

Output

1
1 5

Input

5
1 2 3 4 5

Output

-1

Input

7
1 2 1 3 1 2 1

Output

2
1 3
4 7

```python
n=int(input())
d={}
b=[]
e=1
a=list(map(int,input().split()))
for i in range(n):
	if a[i] in d:
		b.append([e,i+1])
		e=i+2
		d.clear()
	else:
		d[a[i]]=i+1
if len(b)==0:
	print(-1)
	exit()
print(len(b))
k=b[-1]
b[-1]=[k[0],n]
for i in b:
	print(*i)
```


641_B. Little Artem and Matrix

Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.

That element can store information about the matrix of integers size n × m. There are n + m inputs in that element, i.e. each row and each column can get the signal. When signal comes to the input corresponding to some row, this row cyclically shifts to the left, that is the first element of the row becomes last element, second element becomes first and so on. When signal comes to the input corresponding to some column, that column shifts cyclically to the top, that is first element of the column becomes last element, second element becomes first and so on. Rows are numbered with integers from 1 to n from top to bottom, while columns are numbered with integers from 1 to m from left to right.

Artem wants to carefully study this element before using it. For that purpose he is going to set up an experiment consisting of q turns. On each turn he either sends the signal to some input or checks what number is stored at some position of the matrix.

Artem has completed his experiment and has written down the results, but he has lost the chip! Help Artem find any initial matrix that will match the experiment results. It is guaranteed that experiment data is consistent, which means at least one valid matrix exists.

Input

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 100, 1 ≤ q ≤ 10 000) — dimensions of the matrix and the number of turns in the experiment, respectively.

Next q lines contain turns descriptions, one per line. Each description starts with an integer ti (1 ≤ ti ≤ 3) that defines the type of the operation. For the operation of first and second type integer ri (1 ≤ ri ≤ n) or ci (1 ≤ ci ≤ m) follows, while for the operations of the third type three integers ri, ci and xi (1 ≤ ri ≤ n, 1 ≤ ci ≤ m,  - 109 ≤ xi ≤ 109) are given.

Operation of the first type (ti = 1) means that signal comes to the input corresponding to row ri, that is it will shift cyclically. Operation of the second type (ti = 2) means that column ci will shift cyclically. Finally, operation of the third type means that at this moment of time cell located in the row ri and column ci stores value xi.

Output

Print the description of any valid initial matrix as n lines containing m integers each. All output integers should not exceed 109 by their absolute value.

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

Examples

Input

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

Output

8 2
1 8

Input

3 3 2
1 2
3 2 2 5

Output

0 0 0
0 0 5
0 0 0

```python
import itertools
import bisect
import math
from collections import *
import os
import sys
from io import BytesIO, IOBase

ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())

def main():
    n,m,q=mii()
    qq=[]
    for test in range(q):
        pp=lmii()
        qq.append(pp)
    qq.reverse()
    mat=[]
    for i in range(n):
        mat.append([0]*m)
    for i in range(q):
        lst = qq[i]
        if lst[0] == 3:
            mat[lst[1]-1][lst[2]-1] = lst[3]
        elif lst[0] == 2:
            d = deque([])
            for k in range(n):
                d.append(mat[k][lst[1]-1])
            d.appendleft(d.pop())
            for k in range(n):
                mat[k][lst[1]-1]=d[k]
        else:
            d = deque([])
            for k in range(m):
                d.append(mat[lst[1]-1][k])
            d.appendleft(d.pop())
            for k in range(m):
                mat[lst[1]-1][k] = d[k]
    for i in range(n):
        print(*mat[i])
    pass

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

if __name__ == "__main__":
    main()

```


669_E. Little Artem and Time Machine

Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.

Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types:

  1. Add integer to the multiset. Note that the difference between set and multiset is that multiset may store several instances of one integer.
  2. Remove integer from the multiset. Only one instance of this integer is removed. Artem doesn't want to handle any exceptions, so he assumes that every time remove operation is called, that integer is presented in the multiset.
  3. Count the number of instances of the given integer that are stored in the multiset.

But what about time machine? Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there. Consider the following example.

  * First Artem adds integer 5 to the multiset at the 1-st moment of time.
  * Then Artem adds integer 3 to the multiset at the moment 5.
  * Then Artem asks how many 5 are there in the multiset at moment 6. The answer is 1.
  * Then Artem returns back in time and asks how many integers 3 are there in the set at moment 4. Since 3 was added only at moment 5, the number of integers 3 at moment 4 equals to 0.
  * Then Artem goes back in time again and removes 5 from the multiset at moment 3.
  * Finally Artyom asks at moment 7 how many integers 5 are there in the set. The result is 0, since we have removed 5 at the moment 3.

Note that Artem dislikes exceptions so much that he assures that after each change he makes all delete operations are applied only to element that is present in the multiset. The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes.

Help Artem implement time travellers multiset.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of Artem's queries.

Then follow n lines with queries descriptions. Each of them contains three integers ai, ti and xi (1 ≤ ai ≤ 3, 1 ≤ ti, xi ≤ 109) — type of the query, moment of time Artem travels to in order to execute this query and the value of the query itself, respectively. It's guaranteed that all moments of time are distinct and that after each operation is applied all operations of the first and second types are consistent.

Output

For each ask operation output the number of instances of integer being queried at the given moment of time.

Examples

Input

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

Output

1
2
1

Input

3
1 1 1
2 2 1
3 3 1

Output

0

```python
# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

new = lambda xx: (xx|xx-1)+1
def buildBIT(bit,n):
    for i in range(1,n+1):
        x = new(i)
        if x <= n:
            bit[x] += bit[i]

def pointUpdate(bit,point,n,diff):
    while point <= n:
        bit[point] += diff
        point = new(point)

def calculatePrefix(bit,point):
    su = 0
    while point:
        su += bit[point]
        point &= point-1
    return su

def rangeQuery(bit,start,stop):
    # [start,stop]
    return calculatePrefix(bit,stop)-calculatePrefix(bit,start-1)

def compressCoordinate(lst):
    return {i:ind+1 for ind,i in enumerate(sorted(set(lst)))}

def main():
    from collections import defaultdict
    n = int(input())
    dct = defaultdict(list)
    oper = [list(map(int,input().split())) for _ in range(n)]
    for a,t,x in oper:
        dct[x].append(t)
    new = {i:compressCoordinate(dct[i]) for i in dct}
    for i in range(n):
        oper[i][1] = new[oper[i][2]][oper[i][1]]

    bit = {i:[0]*(len(dct[i])+1) for i in dct}
    for a,t,x in oper:
        if a == 1:
            pointUpdate(bit[x],t,len(bit[x])-1,1)
        elif a == 2:
            pointUpdate(bit[x],t,len(bit[x])-1,-1)
        else:
            print(calculatePrefix(bit[x],t))

# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
    main()
```


690_E2. Photographs (II)

Zombies seem to have become much more intelligent lately – a few have somehow wandered into the base through the automatic gate. Heidi has had to beef up security, and a new gate has been installed. Unfortunately, now the questions being asked are more complicated, and even humans have trouble answering them. Can you still program the robot army to do this reliably?

The new questions are of the following form: a grayscale photograph has been divided into several horizontal pieces, which have been arbitrarily rearranged. The task is to assemble the original image back from these pieces (somewhat like in a jigsaw puzzle). To further delay the zombies, significant Gaussian-distributed noise has been added to the image.

Input

The input format is the same as in the previous version, except that the first line of every question now contains three space-separated numbers h, w and k (1 ≤ h, w ≤ 600, 2 ≤ k ≤ 16) – the height (number of rows) and width (number of columns) of the photograph and the number of pieces, respectively. The number of pieces evenly divides the height, and each piece is of the same height h / k.

Again, there is only one input file to be processed, and the same resources are provided to you as in the previous version (except that now you are given all input images in .bmp format, rather than the first 50).

Output

Your program should print q lines. The i-th line should contain your answer for the i-th question: a space-separated sequence of k numbers π1, π2, ..., πk such that:

  * π is a permutation of {1, 2, ..., k}, that is, each number from 1 to k appears exactly once in π,
  * for each j = 1, ..., k, πj is the position (index), in the original image, of the piece which is at position j in the input image. (See the illustration below for clarity.)

<image>

The second image from the test set. If the three pieces in the original image are numbered 1, 2, 3 from top to bottom, then the numbering in the image on the right should be 2, 3, 1. The correct answer for this image is thus 2 3 1.

Again, your answers will be accepted if they conform to this format and if at least 75% of them are correct.

Again, you may process the input locally and submit just your precomputed answers (i.e., a program which just prints your output for the input file all.in).

Note

The link to download all the necessary materials is http://assets.codeforces.com/files/690/medium_contestant_package.zip


715_B. Complete The Graph

ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.

The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?

Input

The first line contains five integers n, m, L, s, t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 10 000, 1 ≤ L ≤ 109, 0 ≤ s, t ≤ n - 1, s ≠ t) — the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.

Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≤ ui, vi ≤ n - 1, ui ≠ vi, 0 ≤ wi ≤ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.

It is guaranteed that there is at most one edge between any pair of vertices.

Output

Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.

Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018.

The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.

If there are multiple solutions, print any of them.

Examples

Input

5 5 13 0 4
0 1 5
2 1 2
3 2 3
1 4 0
4 3 4

Output

YES
0 1 5
2 1 2
3 2 3
1 4 8
4 3 4

Input

2 1 123456789 0 1
0 1 0

Output

YES
0 1 123456789

Input

2 1 999999999 1 0
0 1 1000000000

Output

NO

Note

Here's how the graph in the first sample case looks like :

<image>

In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.

In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.

In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".

```python
import heapq
from collections import defaultdict

class Graph:
    def __init__(self, n):
        self.nodes = set(range(n))
        self.edges = defaultdict(list)
        self.distances = {}

    def add_edge(self, from_node, to_node, distance):
        self.edges[from_node].append(to_node)
        self.edges[to_node].append(from_node)
        self.distances[from_node, to_node] = distance
        self.distances[to_node, from_node] = distance

def dijkstra(graph, initial, end):
    visited = {initial: 0}
    path = {}
    h = [(0, initial)]

    nodes = set(graph.nodes)

    while nodes and h:
        current_weight, min_node = heapq.heappop(h)
        try:
            while min_node not in nodes:
                current_weight, min_node = heapq.heappop(h)
        except IndexError:
            break
        if min_node == end:
            break

        nodes.remove(min_node)

        for v in graph.edges[min_node]:
            weight = current_weight + graph.distances[min_node, v]
            if v not in visited or weight < visited[v]:
                visited[v] = weight
                heapq.heappush(h, (weight, v))
                path[v] = min_node

    return visited, path

n, m, L, s, t = map(int, input().split())
min_g = Graph(n)
max_g = Graph(n)
g = Graph(n)
for _ in range(m):
    u, v, w = map(int, input().split())
    if w == 0:
        min_w = 1
        max_w = int(1e18)
    else:
        min_w = max_w = w
    min_g.add_edge(u, v, min_w)
    max_g.add_edge(u, v, max_w)
    g.add_edge(u, v, w)

min_ls, min_p = dijkstra(min_g, s, t)
try:
    min_l = min_ls[t]
    max_l = dijkstra(max_g, s, t)[0][t]
except KeyError:
    min_l = 0
    max_l = -1
if min_l <= L <= max_l:
    while min_l < L:
        a = s
        b = z = t
        while z != s:
            if g.distances[z, min_p[z]] == 0:
                max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]]
                max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]]
                a = z
                b = min_p[z]
            z = min_p[z]
        new_dist = min_g.distances[a, b] + L - min_l
        max_g.distances[a, b] = new_dist
        max_g.distances[b, a] = new_dist

        min_g = max_g
        min_ls, min_p = dijkstra(min_g, s, t)
        min_l = min_ls[t]

    if min_l == L:
        print('YES')
        print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in min_g.distances.items() if u < v))
    else:
        print('NO')
else:
    print('NO')

```


735_D. Taxes

Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he needs to pay 5 and if n = 2 he pays only 1 burle.

As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial n in several parts n1 + n2 + ... + nk = n (here k is arbitrary, even k = 1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition ni ≥ 2 should hold for all i from 1 to k.

Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split n in parts.

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 2·109) — the total year income of mr. Funt.

Output

Print one integer — minimum possible number of burles that mr. Funt has to pay as a tax.

Examples

Input

4

Output

2

Input

27

Output

3

```python
def isPrime(n):
    i=2
    while i*i<=n:
        if n%i==0:
            return False
        i+=1
    return True

n=int(input())
if isPrime(n):
    print(1)
elif n&1==0:
    print(2)
else:
    if isPrime(n-2):
        print(2)
    else:
        print(3)

```


75_D. Big Maximum Sum

Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.

This problem is similar to a standard problem but it has a different format and constraints.

In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.

But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.

For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.

Can you help Mostafa solve this problem?

Input

The first line contains two integers n and m, n is the number of the small arrays (1 ≤ n ≤ 50), and m is the number of indexes in the big array (1 ≤ m ≤ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≤ l ≤ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n.

The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array.

Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.

Output

Print one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty.

Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).

Examples

Input

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

Output

9

Input

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

Output

8

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

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

def prepare(n, *a):
    acc = 0
    sub_max = -10**9
    left_min = 0
    left_max = 0
    lmin2, lmax2 = 0, -10**9

    for i, x in enumerate(a):
        acc += x
        sub_max = max(sub_max, acc - left_min)
        left_min = min(left_min, acc)
        left_max = max(left_max, acc)
        if i > 0:
            lmax2 = max(lmax2, acc)
        if i < n - 1:
            lmin2 = min(lmin2, acc)

    return left_min, left_max, acc, sub_max, lmin2, lmax2

n, m = map(int, input().split())
small_a = [(0, 0, 0, 0, 0, 0)]

for _ in range(n):
    small_a.append(prepare(*map(int, input().split())))

indexes = tuple(map(int, input().split()))
left_min, _, acc, ans, left_min2, _ = small_a[indexes[0]]

for i in indexes[1:]:
    ans = max(
        ans,
        small_a[i][3],
        acc + small_a[i][1] - left_min2,
        acc + small_a[i][5] - left_min
    )
    left_min2 = min(left_min, acc + small_a[i][4])
    left_min = min(left_min, acc + small_a[i][0])
    acc += small_a[i][2]

print(ans)

```


780_C. Andryusha and Colored Balloons

Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.

The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.

Andryusha wants to use as little different colors as possible. Help him to choose the colors!

Input

The first line contains single integer n (3 ≤ n ≤ 2·105) — the number of squares in the park.

Each of the next (n - 1) lines contains two integers x and y (1 ≤ x, y ≤ n) — the indices of two squares directly connected by a path.

It is guaranteed that any square is reachable from any other using the paths.

Output

In the first line print single integer k — the minimum number of colors Andryusha has to use.

In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.

Examples

Input

3
2 3
1 3

Output

3
1 3 2

Input

5
2 3
5 3
4 3
1 3

Output

5
1 3 2 5 4

Input

5
2 1
3 2
4 3
5 4

Output

3
1 2 3 1 2

Note

In the first sample the park consists of three squares: 1 → 3 → 2. Thus, the balloon colors have to be distinct.

<image> Illustration for the first sample.

In the second example there are following triples of consequently connected squares:

  * 1 → 3 → 2
  * 1 → 3 → 4
  * 1 → 3 → 5
  * 2 → 3 → 4
  * 2 → 3 → 5
  * 4 → 3 → 5

We can see that each pair of squares is encountered in some triple, so all colors have to be distinct. <image> Illustration for the second sample.

In the third example there are following triples:

  * 1 → 2 → 3
  * 2 → 3 → 4
  * 3 → 4 → 5

We can see that one or two colors is not enough, but there is an answer that uses three colors only. <image> Illustration for the third sample.

```python
n=int(input())
g=[[] for i in range(n)]
for _ in range(n-1):
  x,y=map(int,input().split())
  g[x-1].append(y-1)
  g[y-1].append(x-1)
l=0
for i in range(n):
  l=max(l,len(g[i])+1)
q=[0]
paint=[-1]*n
paint[0]=1
while q:
  ver=q.pop()
  use=set()
  use.add(paint[ver])
  for to in g[ver]:
    use.add(paint[to])
  arr=[]
  for i in range(1,l+1):
    if not i in use:
      arr.append(i)
    if len(arr)==len(g[ver]):
      break
  for to in g[ver]:
    if paint[to]==-1:
      for j in range(1,l+1):
        if not j in use:
          paint[to]=arr[-1]
          q.append(to)
          arr.pop()
          break
print(l)
print(*paint)
```