901_C. Bipartite Segments

You are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n.

You have to answer q queries. Each query is described by a segment of vertices [l; r], and you have to count the number of its subsegments [x; y] (l ≤ x ≤ y ≤ r), such that if we delete all vertices except the segment of vertices [x; y] (including x and y) and edges between them, the resulting graph is bipartite.

Input

The first line contains two integers n and m (1 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105) — the number of vertices and the number of edges in the graph.

The next m lines describe edges in the graph. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting an edge between vertices ai and bi. It is guaranteed that this graph does not contain edge-simple cycles of even length.

The next line contains a single integer q (1 ≤ q ≤ 3·105) — the number of queries.

The next q lines contain queries. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n) — the query parameters.

Output

Print q numbers, each in new line: the i-th of them should be the number of subsegments [x; y] (li ≤ x ≤ y ≤ ri), such that the graph that only includes vertices from segment [x; y] and edges between them is bipartite.

Examples

Input

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

Output

5
5
14

Input

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

Output

27
8
19

Note

The first example is shown on the picture below:

<image>

For the first query, all subsegments of [1; 3], except this segment itself, are suitable.

For the first query, all subsegments of [4; 6], except this segment itself, are suitable.

For the third query, all subsegments of [1; 6] are suitable, except [1; 3], [1; 4], [1; 5], [1; 6], [2; 6], [3; 6], [4; 6].

The second example is shown on the picture below:

<image>

```python

def divisors(M):
    d=[]
    i=1
    while M>=i**2:
        if M%i==0:
            d.append(i)
            if i**2!=M:
                d.append(M//i)
        i=i+1
    return d

def popcount(x):
    x = x - ((x >> 1) & 0x55555555)
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    return x & 0x0000007f

def eratosthenes(n):
    res=[0 for i in range(n+1)]
    prime=set([])
    for i in range(2,n+1):
        if not res[i]:
            prime.add(i)
            for j in range(1,n//i+1):
                res[i*j]=1
    return prime

def factorization(n):
    res=[]
    for p in prime:
        if n%p==0:
            while n%p==0:
                n//=p
            res.append(p)
    if n!=1:
        res.append(n)
    return res

def euler_phi(n):
    res = n
    for x in range(2,n+1):
        if x ** 2 > n:
            break
        if n%x==0:
            res = res//x * (x-1)
            while n%x==0:
                n //= x
    if n!=1:
        res = res//n * (n-1)
    return res

def ind(b,n):
    res=0
    while n%b==0:
        res+=1
        n//=b
    return res

def isPrimeMR(n):
    d = n - 1
    d = d // (d & -d)
    L = [2, 3, 5, 7, 11, 13, 17]
    for a in L:
        t = d
        y = pow(a, t, n)
        if y == 1: continue
        while y != n - 1:
            y = (y * y) % n
            if y == 1 or t == n - 1: return 0
            t <<= 1
    return 1
def findFactorRho(n):
    from math import gcd
    m = 1 << n.bit_length() // 8
    for c in range(1, 99):
        f = lambda x: (x * x + c) % n
        y, r, q, g = 2, 1, 1, 1
        while g == 1:
            x = y
            for i in range(r):
                y = f(y)
            k = 0
            while k < r and g == 1:
                ys = y
                for i in range(min(m, r - k)):
                    y = f(y)
                    q = q * abs(x - y) % n
                g = gcd(q, n)
                k += m
            r <<= 1
        if g == n:
            g = 1
            while g == 1:
                ys = f(ys)
                g = gcd(abs(x - ys), n)
        if g < n:
            if isPrimeMR(g): return g
            elif isPrimeMR(n // g): return n // g
            return findFactorRho(g)
def primeFactor(n):
    i = 2
    ret = {}
    rhoFlg = 0
    while i*i <= n:
        k = 0
        while n % i == 0:
            n //= i
            k += 1
        if k: ret[i] = k
        i += 1 + i % 2
        if i == 101 and n >= 2 ** 20:
            while n > 1:
                if isPrimeMR(n):
                    ret[n], n = 1, 1
                else:
                    rhoFlg = 1
                    j = findFactorRho(n)
                    k = 0
                    while n % j == 0:
                        n //= j
                        k += 1
                    ret[j] = k

    if n > 1: ret[n] = 1
    if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
    return ret

def divisors(n):
    res = [1]
    prime = primeFactor(n)
    for p in prime:
        newres = []
        for d in res:
            for j in range(prime[p]+1):
                newres.append(d*p**j)
        res = newres
    res.sort()
    return res

def xorfactorial(num):
    if num==0:
        return 0
    elif num==1:
        return 1
    elif num==2:
        return 3
    elif num==3:
        return 0
    else:
        x=baseorder(num)
        return (2**x)*((num-2**x+1)%2)+function(num-2**x)

def xorconv(n,X,Y):
    if n==0:
        res=[(X[0]*Y[0])%mod]
        return res
    x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
    y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
    z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
    w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
    res1=xorconv(n-1,x,y)
    res2=xorconv(n-1,z,w)
    former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
    latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
    former=list(map(lambda x:x%mod,former))
    latter=list(map(lambda x:x%mod,latter))
    return former+latter

def merge_sort(A,B):
    pos_A,pos_B = 0,0
    n,m = len(A),len(B)
    res = []
    while pos_A < n and pos_B < m:
        a,b = A[pos_A],B[pos_B]
        if a < b:
            res.append(a)
            pos_A += 1
        else:
            res.append(b)
            pos_B += 1
    res += A[pos_A:]
    res += B[pos_B:]
    return res

class UnionFindVerSize():
    def __init__(self, N):
        self._parent = [n for n in range(0, N)]
        self._size = [1] * N
        self.group = N

    def find_root(self, x):
        if self._parent[x] == x: return x
        self._parent[x] = self.find_root(self._parent[x])
        stack = [x]
        while self._parent[stack[-1]]!=stack[-1]:
            stack.append(self._parent[stack[-1]])
        for v in stack:
            self._parent[v] = stack[-1]
        return self._parent[x]

    def unite(self, x, y):
        gx = self.find_root(x)
        gy = self.find_root(y)
        if gx == gy: return

        self.group -= 1

        if self._size[gx] < self._size[gy]:
            self._parent[gx] = gy
            self._size[gy] += self._size[gx]
        else:
            self._parent[gy] = gx
            self._size[gx] += self._size[gy]

    def get_size(self, x):
        return self._size[self.find_root(x)]

    def is_same_group(self, x, y):
        return self.find_root(x) == self.find_root(y)

class WeightedUnionFind():
    def __init__(self,N):
        self.parent = [i for i in range(N)]
        self.size = [1 for i in range(N)]
        self.val = [0 for i in range(N)]
        self.flag = True
        self.edge = [[] for i in range(N)]

    def dfs(self,v,pv):
        stack = [(v,pv)]
        new_parent = self.parent[pv]
        while stack:
            v,pv = stack.pop()
            self.parent[v] = new_parent
            for nv,w in self.edge[v]:
                if nv!=pv:
                    self.val[nv] = self.val[v] + w
                    stack.append((nv,v))

    def unite(self,x,y,w):
        if not self.flag:
            return
        if self.parent[x]==self.parent[y]:
            self.flag = (self.val[x] - self.val[y] == w)
            return

        if self.size[self.parent[x]]>self.size[self.parent[y]]:
            self.edge[x].append((y,-w))
            self.edge[y].append((x,w))
            self.size[x] += self.size[y]
            self.val[y] = self.val[x] - w
            self.dfs(y,x)
        else:
            self.edge[x].append((y,-w))
            self.edge[y].append((x,w))
            self.size[y] += self.size[x]
            self.val[x] = self.val[y] + w
            self.dfs(x,y)

class Dijkstra():
    class Edge():
        def __init__(self, _to, _cost):
            self.to = _to
            self.cost = _cost

    def __init__(self, V):
        self.G = [[] for i in range(V)]
        self._E = 0
        self._V = V

    @property
    def E(self):
        return self._E

    @property
    def V(self):
        return self._V

    def add_edge(self, _from, _to, _cost):
        self.G[_from].append(self.Edge(_to, _cost))
        self._E += 1

    def shortest_path(self, s):
        import heapq
        que = []
        d = [10**15] * self.V
        d[s] = 0
        heapq.heappush(que, (0, s))

        while len(que) != 0:
            cost, v = heapq.heappop(que)
            if d[v] < cost: continue

            for i in range(len(self.G[v])):
                e = self.G[v][i]
                if d[e.to] > d[v] + e.cost:
                    d[e.to] = d[v] + e.cost
                    heapq.heappush(que, (d[e.to], e.to))
        return d

#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
    N = len(s)
    Z_alg = [0]*N

    Z_alg[0] = N
    i = 1
    j = 0
    while i < N:
        while i+j < N and s[j] == s[i+j]:
            j += 1
        Z_alg[i] = j
        if j == 0:
            i += 1
            continue
        k = 1
        while i+k < N and k + Z_alg[k]<j:
            Z_alg[i+k] = Z_alg[k]
            k += 1
        i += k
        j -= k
    return Z_alg

class BIT():
    def __init__(self,n,mod=0):
        self.BIT = [0]*(n+1)
        self.num = n
        self.mod = mod

    def query(self,idx):
        res_sum = 0
        mod = self.mod
        while idx > 0:
            res_sum += self.BIT[idx]
            if mod:
                res_sum %= mod
            idx -= idx&(-idx)
        return res_sum

    #Ai += x O(logN)
    def update(self,idx,x):
        mod = self.mod
        while idx <= self.num:
            self.BIT[idx] += x
            if mod:
                self.BIT[idx] %= mod
            idx += idx&(-idx)
        return

class dancinglink():
    def __init__(self,n,debug=False):
        self.n = n
        self.debug = debug
        self._left = [i-1 for i in range(n)]
        self._right = [i+1 for i in range(n)]
        self.exist = [True for i in range(n)]

    def pop(self,k):
        if self.debug:
            assert self.exist[k]
        L = self._left[k]
        R = self._right[k]
        if L!=-1:
            if R!=self.n:
                self._right[L],self._left[R] = R,L
            else:
                self._right[L] = self.n
        elif R!=self.n:
            self._left[R] = -1
        self.exist[k] = False

    def left(self,idx,k=1):
        if self.debug:
            assert self.exist[idx]
        res = idx
        while k:
            res = self._left[res]
            if res==-1:
                break
            k -= 1
        return res

    def right(self,idx,k=1):
        if self.debug:
            assert self.exist[idx]
        res = idx
        while k:
            res = self._right[res]
            if res==self.n:
                break
            k -= 1
        return res

class SparseTable():
    def __init__(self,A,merge_func,ide_ele):
        N=len(A)
        n=N.bit_length()
        self.table=[[ide_ele for i in range(n)] for i in range(N)]
        self.merge_func=merge_func

        for i in range(N):
            self.table[i][0]=A[i]

        for j in range(1,n):
            for i in range(0,N-2**j+1):
                f=self.table[i][j-1]
                s=self.table[i+2**(j-1)][j-1]
                self.table[i][j]=self.merge_func(f,s)

    def query(self,s,t):
        b=t-s+1
        m=b.bit_length()-1
        return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])

class BinaryTrie:
    class node:
        def __init__(self,val):
            self.left = None
            self.right = None
            self.max = val

    def __init__(self):
        self.root = self.node(-10**15)

    def append(self,key,val):
        pos = self.root
        for i in range(29,-1,-1):
            pos.max = max(pos.max,val)
            if key>>i & 1:
                if pos.right is None:
                    pos.right = self.node(val)
                    pos = pos.right
                else:
                    pos = pos.right
            else:
                if pos.left is None:
                    pos.left = self.node(val)
                    pos = pos.left
                else:
                    pos = pos.left
        pos.max = max(pos.max,val)

    def search(self,M,xor):
        res = -10**15
        pos = self.root
        for i in range(29,-1,-1):
            if pos is None:
                break

            if M>>i & 1:
                if xor>>i & 1:
                    if pos.right:
                        res = max(res,pos.right.max)
                    pos = pos.left
                else:
                    if pos.left:
                        res = max(res,pos.left.max)
                    pos = pos.right
            else:
                if xor>>i & 1:
                    pos = pos.right
                else:
                    pos = pos.left

        if pos:
            res = max(res,pos.max)
        return res

def solveequation(edge,ans,n,m):
    #edge=[[to,dire,id]...]
    x=[0]*m
    used=[False]*n
    for v in range(n):
        if used[v]:
            continue
        y = dfs(v)
        if y!=0:
            return False
    return x

    def dfs(v):
        used[v]=True
        r=ans[v]
        for to,dire,id in edge[v]:
            if used[to]:
                continue
            y=dfs(to)
            if dire==-1:
                x[id]=y
            else:
                x[id]=-y
            r+=y
        return r

class SegmentTree:
    def __init__(self, init_val, segfunc, ide_ele):
        n = len(init_val)
        self.segfunc = segfunc
        self.ide_ele = ide_ele
        self.num = 1 << (n - 1).bit_length()
        self.tree = [ide_ele] * 2 * self.num
        self.size = n
        for i in range(n):
            self.tree[self.num + i] = init_val[i]
        for i in range(self.num - 1, 0, -1):
            self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

    def update(self, k, x):
        k += self.num
        self.tree[k] = x
        while k > 1:
            self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
            k >>= 1

    def query(self, l, r):
        if r==self.size:
            r = self.num

        res = self.ide_ele

        l += self.num
        r += self.num
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

    def bisect_l(self,l,r,x):
        l += self.num
        r += self.num
        Lmin = -1
        Rmin = -1
        while l<r:
            if l & 1:
                if self.tree[l] <= x and Lmin==-1:
                    Lmin = l
                l += 1
            if r & 1:
                if self.tree[r-1] <=x:
                    Rmin = r-1
            l >>= 1
            r >>= 1

        if Lmin != -1:
            pos = Lmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos = 2 * pos +1
            return pos-self.num
        elif Rmin != -1:
            pos = Rmin
            while pos<self.num:
                if self.tree[2 * pos] <=x:
                    pos = 2 * pos
                else:
                    pos = 2 * pos +1
            return pos-self.num
        else:
            return -1

import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log

import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
mi = lambda :map(int,input().split())
li = lambda :list(mi())

n,m = mi()
edge = [[] for i in range(n)]
for _ in range(m):
    u,v = mi()
    edge[u-1].append(v-1)
    edge[v-1].append(u-1)

parent = [-1 for i in range(n)]
depth = [0 for i in range(n)]
cnt = [0 for i in range(n)]

res = [n for i in range(n)]

for root in range(n):
    if parent[root]==-1:
        stack = [root]
        while stack:
            v = stack[-1]
            if len(edge[v])==cnt[v]:
                stack.pop()
            else:
                nv = edge[v][cnt[v]]
                cnt[v] += 1
                if nv==root or parent[nv]!=-1:
                    if depth[nv] < depth[v]-1:
                        m,M = nv,nv
                        pos = v
                        while pos!=nv:
                            m = min(pos,m)
                            M = max(pos,M)
                            pos = parent[pos]
                        res[m] = min(res[m],M)
                else:
                    depth[nv] = depth[v] + 1
                    parent[nv] = v
                    stack.append(nv)

cnt = [0 for i in range(n)]
cnt[n-1] = res[n-1] - (n-1)
for i in range(n-2,-1,-1):
    res[i] = min(res[i],res[i+1])
    cnt[i] = res[i] - i

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

query = [[] for i in range(n+1)]
q = int(input())
for i in range(q):
    l,r = mi()
    query[r].append((i,l-1))

pos = -1
ans = [0 for i in range(q)]
for r in range(1,n+1):
    while pos+1<n and res[pos+1]<=r:
        pos += 1
    for idx,l in query[r]:
        if r<=pos:
            tmp = cnt[r-1]
            if l:
                tmp -= cnt[l-1]
        elif l<=pos:
            tmp = cnt[pos]
            if l:
                tmp -= cnt[l-1]
            tmp += (r-pos-1) * r - ((r+pos)*(r-pos-1)//2)
        else:
            tmp = (r-l) * r - ((r-1+l)*(r-l)//2)
        ans[idx] = tmp

print(*ans,sep="\n")

```


952_B. A Map of the Cat

If you have ever interacted with a cat, you have probably noticed that they are quite particular about how to pet them. Here is an approximate map of a normal cat.

<image>

However, some cats won't tolerate this nonsense from the humans. Here is a map of a grumpy cat.

<image>

You have met a cat. Can you figure out whether it's normal or grumpy?

Interaction

This is an interactive problem. Initially you're not given any information about the cat. Instead, the cat is divided into ten areas, indexed from 0 to 9.

In one query you can choose which area you'll pet and print the corresponding index to standard out. You will get the cat's response, as depicted on the corresponding map, via standard in. For simplicity all responses are written in lowercase.

Once you're certain what type of cat you're dealing with, output "normal" or "grumpy" to standard out.

Note

Please make sure to use the stream flushing operation after each query in order not to leave part of your output in some buffer.

```python
#copy marsi bal !
print('grumpy' if input('9\n')[-2:] in ['s?', 'le', 'se', 'ay', 'en'] else 'normal')
```


999_E. Reachability from the Capital

There are n cities and m roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.

What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?

New roads will also be one-way.

Input

The first line of input consists of three integers n, m and s (1 ≤ n ≤ 5000, 0 ≤ m ≤ 5000, 1 ≤ s ≤ n) — the number of cities, the number of roads and the index of the capital. Cities are indexed from 1 to n.

The following m lines contain roads: road i is given as a pair of cities u_i, v_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i). For each pair of cities (u, v), there can be at most one road from u to v. Roads in opposite directions between a pair of cities are allowed (i.e. from u to v and from v to u).

Output

Print one integer — the minimum number of extra roads needed to make all the cities reachable from city s. If all the cities are already reachable from s, print 0.

Examples

Input

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

Output

3

Input

5 4 5
1 2
2 3
3 4
4 1

Output

1

Note

The first example is illustrated by the following:

<image>

For example, you can add roads (6, 4), (7, 9), (1, 7) to make all the cities reachable from s = 1.

The second example is illustrated by the following:

<image>

In this example, you can add any one of the roads (5, 1), (5, 2), (5, 3), (5, 4) to make all the cities reachable from s = 5.

```python
def main():
    import sys
    sys.setrecursionlimit(10**5)
    from collections import deque
    n, m, s = map(int, input().split())
    s -= 1
    graph = [[] for _ in range(n)]
    for _ in range(m):
        u, v = map(int, input().split())
        graph[u-1].append(v-1)

    seen = [False]*n
    li = deque()

    def visit(node):
        if not seen[node]:
            seen[node] = True
            for c_node in graph[node]:
                visit(c_node)
            li.appendleft(node)

    def visit2(node):
        if not seen[node]:
            seen[node] = True
            for c_node in graph[node]:
                visit2(c_node)

    for i in range(n):
        visit(i)
    seen = [False]*n
    cnt = 0
    visit2(s)
    for i in li:
        if seen[i]:
            continue
        visit2(i)
        cnt += 1
    print(cnt)

if __name__ == "__main__":
    try:
        main()
    except:
        print('error!')
        exit(0)
```


p02536 ACL Beginner Contest - Connect Cities

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M. Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

* Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

* 2 \leq N \leq 100,000
* 1 \leq M \leq 100,000
* 1 \leq A_i < B_i \leq N
* No two roads connect the same pair of cities.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Example

Input

3 1
1 2

Output

1

```python
from collections import deque

N, M = map(int, input().split())

AB = [[] for _ in range(N)]

for _ in range(M):
    a,b = map(lambda x: int(x)-1, input().split())
    AB[a].append(b)
    AB[b].append(a)

visited = [0] * N
ans = []
for i in range(N):
    if visited[i]:
        continue
    group = [i]
    d = deque(AB[i])
    while d:
        s = d.popleft()
        if visited[s]:
            continue
        visited[s] = 1
        group.append(s)
        for k in AB[s]:
            d.append(k)
    ans.append(len(group))

print(len(ans)-1)

```


p02667 NOMURA Programming Competition 2020 - Binary Programming

Takahashi has an empty string S and a variable x whose initial value is 0.

Also, we have a string T consisting of `0` and `1`.

Now, Takahashi will do the operation with the following two steps |T| times.

* Insert a `0` or a `1` at any position of S of his choice.
* Then, increment x by the sum of the digits in the odd positions (first, third, fifth, ...) of S. For example, if S is `01101`, the digits in the odd positions are `0`, `1`, `1` from left to right, so x is incremented by 2.

Print the maximum possible final value of x in a sequence of operations such that S equals T in the end.

Constraints

* 1 \leq |T| \leq 2 \times 10^5
* T consists of `0` and `1`.

Input

Input is given from Standard Input in the following format:

T

Output

Print the maximum possible final value of x in a sequence of operations such that S equals T in the end.

Examples

Input

1101

Output

5

Input

0111101101

Output

26

```python
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

T = read().rstrip().decode()

T

def f(n, r, l, z):
    # 長さnの1が座標 r から l へと移動する。
    # z回立ち止まることが許されている。
    # 獲得スコアの最大値は？
    if n % 2 == 0:
        move = r - l + z
        return (move + 1) * (n // 2)
    if r == l and r % 2 == 0:
        # ev, od, ev, od, evで固定
        k = (n - 1) // 2
        move = r - l + z
        return (move + 1) * k
    # 各地点に1回ずつ立ち寄りつつ、奇数のところでz回足踏みできる
    ev = (r // 2) - ((l - 1) // 2)
    od = (r - l + 1) - ev
    od += z
    k = (n - 1) // 2
    return ev * k + od * (k + 1)

Z = T.count('0')
one = 0
to = 0
answer = 0
for i, x in enumerate(T, 1):
    if x == '0':
        if one:
            answer += f(one, i - 1, to, Z)
            one = 0
        Z -= 1
        continue
    to += 1
    one += 1
if one:
    answer += f(one, i, to, Z)

def f(n):
    # '1' * n から減らしたときのスコア
    # ただし、最初は除く
    ret = 0
    for i in range(0, n, 2):
        ret += (n - i)
    ret -= (n + 1) // 2
    return ret

n = T.count('1')
answer += f(n)
print(answer)
```


p02796 Keyence Programming Contest 2020 - Robot Arms

In a factory, there are N robots placed on a number line. Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.

We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect. Here, for each i (1 \leq i \leq N), the movable range of arms of Robot i is the part of the number line between the coordinates X_i - L_i and X_i + L_i, excluding the endpoints.

Find the maximum number of robots that we can keep.

Constraints

* 1 \leq N \leq 100,000
* 0 \leq X_i \leq 10^9 (1 \leq i \leq N)
* 1 \leq L_i \leq 10^9 (1 \leq i \leq N)
* If i \neq j, X_i \neq X_j.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 L_1
X_2 L_2
\vdots
X_N L_N

Output

Print the maximum number of robots that we can keep.

Examples

Input

4
2 4
4 3
9 3
100 5

Output

3

Input

2
8 20
1 10

Output

1

Input

5
10 1
2 1
4 1
6 1
8 1

Output

5

```python
N=int(input())
xl=[]
for i in range(N):
  x,l=map(int,input().split())
  xl.append([x-l,x+l])

XL=sorted(xl,key=lambda x:x[1])

w=1
robot=XL[0]
for i in XL:
  if robot[1] <= i[0]:
    w+=1
    robot=i
print(w)
```


p02932 Japanese Student Championship 2019 Qualification - Candy Retribution

Find the number of sequences of N non-negative integers A_1, A_2, ..., A_N that satisfy the following conditions:

* L \leq A_1 + A_2 + ... + A_N \leq R
* When the N elements are sorted in non-increasing order, the M-th and (M+1)-th elements are equal.

Since the answer can be enormous, print it modulo 10^9+7.

Constraints

* All values in input are integers.
* 1 \leq M < N \leq 3 \times 10^5
* 1 \leq L \leq R \leq 3 \times 10^5

Input

Input is given from Standard Input in the following format:

N M L R

Output

Print the number of sequences of N non-negative integers, modulo 10^9+7.

Examples

Input

4 2 3 7

Output

105

Input

2 1 4 8

Output

3

Input

141592 6535 89793 238462

Output

933832916

```python
MOD = 10**9+7

kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

N,M,L,R = map(int,input().split())

P = [0 for i in range(R+1)]
Q = [0 for i in range(R+1)]
Z = [0 for i in range(R+1)]
for k in range(1,R+1):
  u = (R-M*k)//k
  for j in range(u+1):
    P[k*j+M*k] += nCr(N-M,j)*(-1)**(j%2)
    P[k*j+M*k] %= MOD
for k in range(R+1):
  Q[k] += nCr(k+N,N)
  Q[k] %= MOD
  Z[k] += nCr(k+N,N)
  Z[k] %= MOD
for k in range(R-M+1):
  Q[k+M] -= nCr(k+N,N)
  Q[k+M] %= MOD

def f(MAX):
  ans = 0
  for t in range(MAX+1):
    ans += P[t]*Q[MAX-t]
    ans %= MOD
  return ans

def F(x):
  return (Z[x]-nCr(N,M)*f(x))%MOD

print((F(R)-F(L-1))%MOD)
```


You are given a string S of length N consisting of lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.

Constraints

* 1 \leq K \leq N\leq 10
* S is a string of length N consisting of lowercase English letters.
* N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.

Examples

Input

5
error
2

Output

*rr*r

Input

6
eleven
5

Output

e*e*e*

Input

9
education
7

Output

******i**

```python
N=int(input())
S=input()
K=int(input())
print("".join(s if s==S[K-1] else "*" for s in S))
```


p03211 AtCoder Beginner Contest 114 - 754

There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is 753. The closer to this number, the better. What is the minimum possible (absolute) difference between X and 753?

Constraints

* S is a string of length between 4 and 10 (inclusive).
* Each character in S is `1`, `2`, ..., or `9`.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible difference between X and 753.

Examples

Input

1234567876

Output

34

Input

35753

Output

0

Input

1111111111

Output

642

```python
s=input()
t=753
for i in range(len(s)-2):
    t=min(t,abs(753-int(s[i:i+3])))
print(t)

```


p03360 AtCoder Beginner Contest 096 - Maximum Sum

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

* Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

* A, B and C are integers between 1 and 50 (inclusive).
* K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Examples

Input

5 3 11
1

Output

30

Input

3 3 4
2

Output

22

```python
l = list(map(int, input().split()))
k = int(input())

print(max(l)*2**k + sum(l)-max(l))
```


p03683 AtCoder Regular Contest 076 - Reconciled?

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that). Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

* 1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Examples

Input

2 2

Output

8

Input

3 2

Output

12

Input

1 8

Output

0

Input

100000 100000

Output

530123477

```python
import sys

def main():
    line = sys.stdin.readline()
    lst = line.split(' ')
    a = int(lst[0])
    b = int(lst[1])
    n = min(a,b)
    m = max(a,b)

    if (m == n+1):
    #n! * m!

        ans = 1
        for i in range(1,n+1):
            ans = (ans * i) % 1000000007

        for i in range(1,m+1):
            ans = (ans * i) % 1000000007

        print(ans)
    elif (m == n):
        ans = 2
        for i in range(1,n+1):
            ans = (ans * i) % 1000000007

        for i in range(1,m+1):
            ans = (ans * i) % 1000000007
        print(ans)
    else:
        print(0)
    return 0

if __name__ == '__main__':
    sys.exit(main())

```


p03836 AtCoder Beginner Contest 051 - Back and Forth

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.
Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.
Here, both the x- and y-coordinates before and after each movement must be integers.
He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).
Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).
Under this condition, find a shortest path for him.

Constraints

* -1000 ≤ sx < tx ≤ 1000
* -1000 ≤ sy < ty ≤ 1000
* sx,sy,tx and ty are integers.

Input

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

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.
The i-th character in S should correspond to his i-th movement.
The directions of the movements should be indicated by the following characters:

* `U`: Up
* `D`: Down
* `L`: Left
* `R`: Right

If there exist multiple shortest paths under the condition, print any of them.

Examples

Input

0 0 1 2

Output

UURDDLLUUURRDRDDDLLU

Input

-2 -2 1 1

Output

UURRURRDDDLLDLLULUUURRURRDDDLLDL


p04003 AtCoder Regular Contest 061 - Snuke's Subway Trip

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

* 2 \leq N \leq 10^5
* 0 \leq M \leq 2×10^5
* 1 \leq p_i \leq N (1 \leq i \leq M)
* 1 \leq q_i \leq N (1 \leq i \leq M)
* 1 \leq c_i \leq 10^6 (1 \leq i \leq M)
* p_i \neq q_i (1 \leq i \leq M)

Input

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

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print `-1` instead.

Examples

Input

3 3
1 2 1
2 3 1
3 1 2

Output

1

Input

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

Output

2

Input

2 0

Output

-1

```python
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)

def read_int():
    return int(input())

def read_int_n():
    return list(map(int, input().split()))

def read_float():
    return float(input())

def read_float_n():
    return list(map(float, input().split()))

def read_str():
    return input().strip()

def read_str_n():
    return list(map(str, input().split()))

def error_print(*args):
    print(*args, file=sys.stderr)

def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap

def bfs01(g, s):
    d = {}
    for v in g.keys():
        d[v] = sys.maxsize
    d[s] = 0

    if s not in d:
        return d
    q = deque()
    q.append((d[s], s))

    NM = 1 << 30
    while q:
        _, u = q.popleft()
        for v in g[u]:
            if v > NM:
                c = 0
            else:
                c = 1
            alt = c + d[u]
            if d[v] > alt:
                d[v] = alt
                if c == 0:
                    q.appendleft((d[v], v))
                else:
                    q.append((d[v], v))
    return d

@mt
def slv(N, M):

    g = defaultdict(list)
    NM = 30
    for _ in range(M):
        p, q, c = input().split()
        p = int(p)
        q = int(q)
        c = int(c)

        cp = (c << NM) + p
        cq = (c << NM) + q
        g[cp].append(cq)
        g[cq].append(cp)
        g[cp].append(p)
        g[cq].append(q)
        g[p].append((cp))
        g[q].append((cq))

    d = bfs01(g, 1)
    return -1 if N not in d or d[N] == sys.maxsize else d[N]

def main():
    N, M = read_int_n()

    print(slv(N, M))

if __name__ == '__main__':
    main()

```


p00089 The Shortest Path on A Rhombic Path

<image>

Arrange integers (0 or more and 99 or less) in a rhombus as illustrated in Fig. 1. Create a program that reads the data representing the rhombus and outputs the maximum value of the sum of the integers that pass when starting from the top and proceeding to the bottom according to the following rules.

* At each step, you can proceed to the lower left diagonal or the lower right diagonal.

For example, in the example of Fig. 1, as shown in Fig. 2, when 7,3,8,7,5,7,8,3,7 is selected and passed, the sum is the maximum 55 (7 + 3 + 8). + 7 + 5 + 7 + 8 + 3 + 7 = 55).

Input

As shown in the input example, a comma-separated sequence of integers is given to the diamond. Each line does not contain whitespace. The input example corresponds to Fig. 1. There are less than 100 rows of data.

Output

Outputs the maximum value of the sum of integers that pass according to the rules on one line.

Example

Input

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

Output

55

```python
import sys
s=[list(map(int,e.split(',')))for e in sys.stdin]
for i in range(1,len(s)):
 for j in range(len(s[i])):
  t=j-(len(s[i])>len(s[i-1]))
  s[i][j]+=max(s[i-1][t*(j>0):t+2])
print(*s[-1])

```


p00221 FizzBuzz

There is a game that uses numbers called "Fizz Buzz". In this game, multiple players count the numbers one by one, starting with 1, and each player says only one number after the previous player. At that time, you must say "Fizz" if it is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if it is divisible by both. For example, the first 16 statements are as follows:

1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, ・ ・ ・

Taro decided to play "Fizz Buzz" with his friends. Taro and his colleagues decided the rules as follows.

"The wrong person will drop out. The next person will start with the next number after the wrong number. That is, if you say 1, 2, 3, you made a mistake with 3, so you will start with 4."

I play the game according to this rule, but because I am not used to the game, I sometimes do not notice that I made a mistake, and I cannot make a fair decision. So you decided to create a program that outputs the remaining people at the end of the set number of remarks so that Taro and his friends can enjoy this game.

Create a program that inputs the number of players, the number of times spoken during the game, and each statement, and outputs the number of the remaining players at the end of the input in ascending order. However, the players are numbered from 1, and the order of speaking is also from the first player, and when the speaking is completed, the first player will speak again. If the player in turn has already dropped out, the next player will speak. Also, the program must ignore subsequent statements when the player is alone.

Input

A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:

m n
s1
s2
::
sn

The first line gives the number of players m (2 ≤ m ≤ 1000) and the number of remarks n (1 ≤ n ≤ 10000).

The next n lines are given the i-th statement s1. si is an integer, Fizz, Buzz, or a string (up to 8 characters) that indicates FizzBuzz.

The number of datasets does not exceed 50.

Output

For each input dataset, the number of the player remaining when the specified number of remarks is input is output in ascending order.

Example

Input

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

Output

2 3 4 5
1

```python
def fizzbuzz(i):
    if i % 15 == 0:
        return 'FizzBuzz'
    elif i % 5 == 0:
        return 'Buzz'
    elif i % 3 == 0:
        return 'Fizz'
    else:
        return str(i)

import sys
f = sys.stdin

while True:
    m, n = map(int, f.readline().split())
    if m == n == 0:
        break
    member = list(range(1, m + 1))
    s = [f.readline().strip() for _ in range(n)]

    pos = 0
    for i in range(n):
        if s[i] != fizzbuzz(i + 1):
            del member[pos]
            m = len(member)
            if m == 1:
                break
        else:
            pos += 1
        pos %= m

    print(*member)
```


p00735 Monday-Saturday Prime Factors

Chief Judge's log, stardate 48642.5. We have decided to make a problem from elementary number theory. The problem looks like finding all prime factors of a positive integer, but it is not.

A positive integer whose remainder divided by 7 is either 1 or 6 is called a 7N+{1,6} number. But as it is hard to pronounce, we shall call it a Monday-Saturday number.

For Monday-Saturday numbers a and b, we say a is a Monday-Saturday divisor of b if there exists a Monday-Saturday number x such that ax = b. It is easy to show that for any Monday-Saturday numbers a and b, it holds that a is a Monday-Saturday divisor of b if and only if a is a divisor of b in the usual sense.

We call a Monday-Saturday number a Monday-Saturday prime if it is greater than 1 and has no Monday-Saturday divisors other than itself and 1. A Monday-Saturday number which is a prime in the usual sense is a Monday-Saturday prime but the converse does not always hold. For example, 27 is a Monday-Saturday prime although it is not a prime in the usual sense. We call a Monday-Saturday prime which is a Monday-Saturday divisor of a Monday-Saturday number a a Monday-Saturday prime factor of a. For example, 27 is one of the Monday-Saturday prime factors of 216, since 27 is a Monday-Saturday prime and 216 = 27 × 8 holds.

Any Monday-Saturday number greater than 1 can be expressed as a product of one or more Monday-Saturday primes. The expression is not always unique even if differences in order are ignored. For example,  216 = 6 × 6 × 6 = 8 × 27  holds.

Our contestants should write a program that outputs all Monday-Saturday prime factors of each input Monday-Saturday number.

Input

The input is a sequence of lines each of which contains a single Monday-Saturday number. Each Monday-Saturday number is greater than 1 and less than 300000 (three hundred thousand). The end of the input is indicated by a line containing a single digit 1.

Output

For each input Monday-Saturday number, it should be printed, followed by a colon `:' and the list of its Monday-Saturday prime factors on a single line. Monday-Saturday prime factors should be listed in ascending order and each should be preceded by a space. All the Monday-Saturday prime factors should be printed only once even if they divide the input Monday-Saturday number more than once.

Sample Input

205920
262144
262200
279936
299998
1

Output for the Sample Input

205920: 6 8 13 15 20 22 55 99
262144: 8
262200: 6 8 15 20 50 57 69 76 92 190 230 475 575 874 2185
279936: 6 8 27
299998: 299998

Example

Input

205920
262144
262200
279936
299998
1

Output

205920: 6 8 13 15 20 22 55 99
262144: 8
262200: 6 8 15 20 50 57 69 76 92 190 230 475 575 874 2185
279936: 6 8 27
299998: 299998

```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-

def monsat(num):
    L = [False for i in range(num+1)]
    for i in range(0,num,7):
        if i == 1 or i == 0:
            continue
        for d in [-1,1]:
            if L[i+d] == False:
                L[i+d] = True
                for j in range((i+d)*2,num,i+d):
                    if L[j] is False:
                        L[j] = [i+d]
                    else:
                        L[j].append(i+d)
    return L

L = monsat(3*10**5+1)
while True:
    n = int(input())
    if n == 1:
        break
    print(str(n) + ':',n if L[n] is True else ' '.join(map(str,L[n])))
```


p00875 Repeated Substitution with Sed

Do you know "sed," a tool provided with Unix? Its most popular use is to substitute every occurrence of a string  contained in the input string (actually each input line) with another string β. More precisely, it proceeds as follows.

1. Within the input string, every non-overlapping (but possibly adjacent) occurrences of α are marked. If there is more than one possibility for non-overlapping matching, the leftmost one is chosen.
2. Each of the marked occurrences is substituted with β to obtain the output string; other parts of the input string remain intact.

For example, when α is "aa" and β is "bca", an input string "aaxaaa" will produce "bcaxbcaa", but not "aaxbcaa" nor "bcaxabca". Further application of the same substitution to the string "bcaxbcaa" will result in "bcaxbcbca", but this is another substitution, which is counted as the second one.

In this problem, a set of substitution pairs (αi, βi) (i = 1, 2, ... , n), an initial string γ, and a final string δ are given, and you must investigate how to produce δ from γ with a minimum number of substitutions. A single substitution (αi, βi) here means simultaneously substituting all the non-overlapping occurrences of αi, in the sense described above, with βi.

You may use a specific substitution (αi, βi ) multiple times, including zero times.

Input

The input consists of multiple datasets, each in the following format.

n
α1 β1
α2 β2
.
.
.
αn βn
γ δ

n is a positive integer indicating the number of pairs. αi and βi are separated by a single space. You may assume that 1 ≤ |αi| < |βi| ≤ 10 for any i (|s| means the length of the string s), αi ≠ αj for any i ≠ j, n ≤ 10 and 1 ≤ |γ| < |δ| ≤ 10. All the strings consist solely of lowercase letters. The end of the input is indicated by a line containing a single zero.

Output

For each dataset, output the minimum number of substitutions to obtain δ from γ. If δ cannot be produced from γ with the given set of substitutions, output -1.

Example

Input

2
a bb
b aa
a
bbbbbbbb
1
a aa
a
aaaaa
3
ab aab
abc aadc
ad dee
abc
deeeeeeeec
10
a abc
b bai
c acf
d bed
e abh
f fag
g abe
h bag
i aaj
j bbb
a
abacfaabe
0

Output

3
-1
7
4

```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    rr = []

    while True:
        n = I()
        if n == 0:
            break
        a = [LS() for _ in range(n)]
        s = S()
        k = S()
        l = len(k)
        if s == k:
            rr.append(0)
            continue
        u = set([s])
        c = set([s])
        t = 0
        r = -1
        while c:
            t += 1
            ns = set()
            for cs in c:
                for d,e in a:
                    nt = cs.replace(d,e)
                    if len(nt) > l:
                        continue
                    ns.add(nt)
            if k in ns:
                r = t
                break
            c = ns - u
            u |= ns
        rr.append(r)

    return '\n'.join(map(str,rr))

print(main())

```


p01138 Osaki

Osaki

Osaki

English text is not available in this practice contest.

The Yamanote Line is a circular railway line laid in the 23 wards of Tokyo. The total route distance is 34.5km, and one lap takes about one hour. There are 29 stations in total. The line color is Uguisu color. The peak congestion rate exceeds 200%, making it one of the busiest railway lines in Japan. One train runs every three minutes during the busiest hours, and people who come to Tokyo for the first time are amazed at the sight.

Mr. Tetsuko loves the Yamanote Line and loves genuine railways. One day, she came up with the following question while reading her favorite book, the JR timetable. "How many vehicles are used a day on the Yamanote Line?"

She tried to figure out the minimum number of vehicles required for operation from the timetable. However, the number of trains was so large that she couldn't count it by herself. So she turned to you, a good programmer, for help.

Your job is to write a program to find the minimum number of cars required to operate the Yamanote Line from a given timetable. Since the Yamanote Line is a circular line, the timetable is often written with "Osaki Station" as the starting and ending stations for convenience. Therefore, only the departure and arrival times of each train at Osaki Station are recorded in the timetable given by her.

Although this cannot happen on the actual Yamanote Line, in order to simplify the situation setting, we will consider that the train can depart from Osaki Station immediately after it arrives at Osaki Station. In addition, there are cases where the time taken by Mr. Tetsuko is incorrect, or the train added by Mr. Tetsuko's delusion is mixed in the timetable, but you can not see them, so to the last The number must be calculated for the time as written.

If you write a program that works, she may invite you to a date on the train. However, it is up to you to accept or decline the invitation.

Input

The input consists of multiple datasets. Each dataset has the following format.

> n
> hh: mm: ss hh: mm: ss
> hh: mm: ss hh: mm: ss
> ...
> hh: mm: ss hh: mm: ss

The integer n in the first line is the number of trains included in the timetable. This value is guaranteed not to exceed 10,000. The departure time and arrival time of each train at Osaki Station are given in this order on the n lines from the 2nd line to the n + 1st line, and the departure time and arrival time are separated by a single space. Each time is expressed in the format hh: mm: ss, where hh is the hour, mm is the minute, and ss is the second. The range of each value is 0 ≤ hh <24, 0 ≤ mm <60, 0 ≤ ss <60. All of these numbers are prefixed with 0s as needed to be two digits.

Trains that run across 24:00 at night are not included. Therefore, the departure time is always before the arrival time.

The end of input is indicated by n = 0. It is not included in the dataset.

Output

For each dataset, output the minimum number of vehicles required on one line.

Sample Input

3
05:47:15 09:54:40
12:12:59 12:13:00
16:30:20 21:18:53
6
00:00:00 03:00:00
01:00:00 03:00:00
02:00:00 03:00:00
03:00:00 04:00:00
03:00:00 05:00:00
03:00:00 06:00:00
0

Output for the Sample Input

1
3

Example

Input

3
05:47:15 09:54:40
12:12:59 12:13:00
16:30:20 21:18:53
6
00:00:00 03:00:00
01:00:00 03:00:00
02:00:00 03:00:00
03:00:00 04:00:00
03:00:00 05:00:00
03:00:00 06:00:00
0

Output

1
3

```python
while True:
    n = int(input())
    if n == 0: break

    trains = []
    for _ in range(n):
        dept, ariv = input().split()
        trains.append((dept, ariv))
    trains.sort(key=lambda x:x[0])
    dcheck = 0
    usecar = 0
    returntime = []
    for tridx in range(len(trains)):
        new = True
        for ariv in returntime:
            if ariv <= trains[tridx][0]:
                new = False
                returntime.remove(ariv)
                break
        if new: usecar += 1
        returntime.append(trains[tridx][1])
    print(usecar)

```


p01277 Symmetry

Open Binary and Object Group organizes a programming contest every year. Mr. Hex belongs to this group and joins the judge team of the contest. This year, he created a geometric problem with its solution for the contest. The problem required a set of points forming a line-symmetric polygon for the input. Preparing the input for this problem was also his task. The input was expected to cover all edge cases, so he spent much time and attention to make them satisfactory.

However, since he worked with lots of care and for a long time, he got tired before he finished. So He might have made mistakes - there might be polygons not meeting the condition. It was not reasonable to prepare the input again from scratch. The judge team thus decided to find all line-asymmetric polygons in his input and fix them as soon as possible. They asked a programmer, just you, to write a program to find incorrect polygons.

You can assume the following:

* Edges of the polygon must not cross or touch each other except for the end points of adjacent edges.
* It is acceptable for the polygon to have adjacent three vertexes on a line, but in such a case, there must be the vertex symmetric to each of them.

Input

The input consists of a set of points in the following format.

N
x1 y1
x2 y2
...
xN yN

The first line of the input contains an integer N (3 ≤ N ≤ 1000), which denotes the number of points. The following N lines describe each point. The i-th line contains two integers x1, y1 (-10000 ≤ xi, yi ≤ 10000), which denote the coordinates of the i-th point.

Note that, although the points are the vertexes of a polygon, they are given in an artibrary order, not necessarily clockwise or counterclockwise.

Output

Output "Yes" in a line if the points can form a line-symmetric polygon, otherwise output "No".

Examples

Input

4
0 1
1 0
0 0
1 1

Output

Yes

Input

4
0 1
1 -1
0 0
1 1

Output

No

Input

9
-1 1
0 1
1 1
-1 0
0 0
1 0
-1 -1
0 -1
1 -1

Output

No

Input

3
-1 -1
0 0
1 1

Output

No

Input

4
0 2
0 0
-1 0
1 0

Output

Yes

```python
from collections import defaultdict
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def gcd(m, n):
    while n:
        m, n = n, m % n
    return m
def solve():
    N = int(readline())
    P = [list(map(int, readline().split())) for i in range(N)]
    ok = 0
    x0, y0 = P[0]; x1, y1 = P[1]
    for i in range(2, N):
        x2, y2 = P[i]
        if (x1 - x0) * (y2 - y0) != (x2 - x0) * (y1 - y0):
            ok = 1
            break
    if not ok:
        write("No\n")
        return
    A = defaultdict(int)
    B = defaultdict(int)
    for i in range(N):
        xi, yi = P[i]
        for j in range(i):
            xj, yj = P[j]
            dx = xi - xj; dy = yi - yj
            g = gcd(abs(dx), abs(dy))
            dx //= g; dy //= g
            if dy < 0:
                dx = -dx; dy = -dy
            if dx == 0:
                p = xi * dy - yi * dx; q = dy
                g = gcd(abs(p), abs(q))
                p //= g; q //= g
                if q < 0:
                    q = -q; p = -p
                key = (p, 0, q, dx, dy)
            else:
                p = yi * dx - xi * dy; q = dx
                g = gcd(abs(p), abs(q))
                p //= g; q //= g
                if q < 0:
                    q = -q; p = -p
                key = (0, p, q, dx, dy)
            A[key] += 1

            gx = -dy; gy = dx
            if gy < 0:
                gx = -gx; gy = -gy
            if dy == 0:
                p = dy * (yi + yj) + dx * (xi + xj)
                q = 2 * dx
                g = gcd(abs(p), abs(q))
                p //= g; q //= g
                if q < 0:
                    q = -q; p = -p
                key = (p, 0, q, gx, gy)
            else:
                p = dx * (xi + xj) + dy * (yi + yj)
                q = 2 * dy
                g = gcd(abs(p), abs(q))
                p //= g; q //= g
                if q < 0:
                    q = -q; p = -p
                key = (0, p, q, gx, gy)
            B[key] += 1
    ok = 0
    if N % 2 == 0:
        for k, v in B.items():
            if 2*v == N:
                ok = 1
                break
            if 2*v == N-2:
                if A[k] == 1:
                    ok = 1
                    break
    else:
        R = []
        for k, v in B.items():
            if 2*v+1 == N:
                R.append(k)
        ok = 0
        for x0, y0, z0, dx, dy in R:
            cnt = 0
            for x, y in P:
                if dy*(x*z0 - x0) == dx*(y*z0 - y0):
                    cnt += 1
            if cnt == 1:
                ok = 1
                break
    if ok:
        write("Yes\n")
    else:
        write("No\n")
solve()

```


p01447 Earth Invasion Diary of Miyabi-sensei

The Quarkgo Empire Expeditionary Force is an evil organization that plans to invade the Earth. In keeping with the tradition of the invaders, they continued to send monsters at a pace of one every week, targeting the area around Tokyo in Japan. However, each time, five warriors calling themselves the Human Squadron Earth Five appeared, and the monster who was rampaging in the city was easily defeated.

Walzard Thru (Earth name: Genmasa) is a female executive of the Quarkgo Empire Expeditionary Force who is seriously worried about such a situation. She had a headache under a commander who wouldn't learn anything from her weekly defeat, or a genius scientist who repeated some misplaced inventions.

Meanwhile, the next operation was decided to send the blood-sucking monster Dracula to Japan. Dracula is a terrifying monster who turns a blood-sucking human into Dracula. Humans who have been sucked by Dracula also suck the blood of other humans to increase their fellow Dracula. In this way, the strategy is to fill the entire earth with Dracula.

Upon hearing this, Walzard soon realized. This strategy is different from the usual sequel strategy such as taking over a kindergarten bus. It's rare for that bad commander to have devised it, and it has the potential to really conquer the Earth.

The momentum of the game is terrifying. Dracula, who landed on the ground, quickly increased the number of friends. If we went on like this, the invasion of the earth seemed to be just a stone's throw away. However, at that moment, a strong and unpleasant premonition ran through Walzard's mind. No way, if this monster, the original is defeated, his friends will not be wiped out, right?

When I asked the scientist who designed and developed Dracula in a hurry, he was still worried about Walzard. It is designed so that when the original Dracula is destroyed, all humans who have sucked blood will return to their original state. Don't be foolish developer. Why did you add such an extra function!

Walzard jumped to the developer and decided to kick his knee, and immediately started the original recovery work. No matter how much the original and the fake look exactly the same, if nothing is done, it is visible that the rushed Earth Five will see through the original for some reason and be defeated.

According to the developers, all Draculaized humans weigh the same, but the original Dracula is a little heavier. Then you should be able to find the original by using only the balance. You must find and retrieve the original Dracula as soon as possible before the Earth Five appears.

Input

N

The integer N (2 ≤ N ≤ 2,000,000,000) is written on the first line of the input. This represents the total number of Draculas, both original and fake.

Output

In the worst case, how many times is it enough to use the balance to find one original from the N Draculas using the balance? Output the minimum value. However, comparing the weights of several Draculas placed on the left and right plates of the balance is counted as one time.

Examples

Input

8

Output

2

Input

30

Output

4

Input

2000000000

Output

20

```python
N = int(input())
n = 1
ans = 1

while True:
    n *= 3
    if n>=N:
        print(ans)
        break
    ans+=1

```


p01753 Magic Bullet

In 20XX AD, a school competition was held. The tournament has finally left only the final competition. You are one of the athletes in the competition.

The competition you participate in is to compete for the time it takes to destroy all the blue objects placed in the space. Athletes are allowed to bring in competition guns. In the space, there are multiple blue objects, the same number of red objects, and multiple obstacles. There is a one-to-one correspondence between the blue object and the red object, and the blue object must be destroyed by shooting a bullet at the blue object from the coordinates where the red object is placed. The obstacles placed in the space are spherical and the composition is slightly different, but if it is a normal bullet, the bullet will stop there when it touches the obstacle.

The bullet used in the competition is a special bullet called Magic Bullet. This bullet can store magical power, and when the bullet touches an obstacle, it automatically consumes the magical power, and the magic that the bullet penetrates is activated. Due to the difference in the composition of obstacles, the amount of magic required to penetrate and the amount of magic power consumed to activate it are different. Therefore, even after the magic for one obstacle is activated, it is necessary to activate another magic in order to penetrate another obstacle. Also, if the bullet touches multiple obstacles at the same time, magic will be activated at the same time. The amount of magical power contained in the bullet decreases with each magic activation.

While the position and size of obstacles and the amount of magical power required to activate the penetrating magic have already been disclosed, the positions of the red and blue objects have not been disclosed. However, the position of the object could be predicted to some extent from the information of the same competition in the past. You want to save as much magical power as you can, because putting magical power into a bullet is very exhausting. Therefore, assuming the position of the red object and the corresponding blue object, the minimum amount of magical power required to be loaded in the bullet at that time, that is, the magical power remaining in the bullet when reaching the blue object is 0. Let's find the amount of magical power that becomes.

Constraints

* 0 ≤ N ≤ 50
* 1 ≤ Q ≤ 50
* -500 ≤ xi, yi, zi ≤ 500
* 1 ≤ ri ≤ 1,000
* 1 ≤ li ≤ 1016
* -500 ≤ sxj, syj, szj ≤ 500
* -500 ≤ dxj, dyj, dzj ≤ 500
* Obstacles are never stuck in other obstacles
* The coordinates of the object are not inside or on the surface of the obstacle
* Under each assumption, the coordinates of the red object and the blue object do not match.

Input

All inputs are integers. Each number is separated by a single space.

N Q
x1 y1 z1 r1 l1
::
xN yN zN rN lN
sx1 sy1 sz1 dx1 dy1 dz1
::
sxQ syQ szQ dxQ dyQ dzQ

* N is the number of obstacles, and Q is the number of coordinates of the assumed blue and red objects.
* xi, yi, and zi are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the center of the i-th obstacle, respectively.
* ri is the radius of the i-th obstacle.
* li is the amount of magical power consumed by magic to penetrate the i-th obstacle.
* sxj, syj, and szj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the red object in the jth assumption, respectively.
* dxj, dyj, and dzj are the x-coordinate, y-coordinate, and z-coordinate that represent the position of the blue object in the jth assumption, respectively.

Output

Assuming the position of each pair of red objects and the corresponding blue objects, the amount of magical power to be loaded in the bullet is output on one line, assuming that there are only obstacles, red objects, and one pair of blue objects in space. Let's do it. The bullet is supposed to fly in a straight line from the position of the red object to the position of the blue object, and since the size of the bullet is very small, it is treated as a point.

Examples

Input

5 1
0 10 0 5 2
0 20 0 5 12
0 30 0 5 22
0 40 0 5 32
0 50 0 5 42
0 0 0 0 60 0

Output

110

Input

1 1
10 5 0 5 9
0 0 0 9 12 0

Output

9

Input

5 5
-38 -71 -293 75 1
-158 -38 -405 66 1
-236 -303 157 266 1
316 26 411 190 1
207 -312 -27 196 1
-50 292 -375 -401 389 -389
460 278 409 -329 -303 411
215 -220 -200 309 -474 300
261 -494 -87 -300 123 -463
386 378 486 -443 -64 299

Output

0
2
1
3
0

```python
N, Q = map(int, input().split())
x = [None] * N
y = [None] * N
z = [None] * N
r = [None] * N
l = [None] * N
for i in range(N):
    x[i], y[i], z[i], r[i], l[i] = map(int, input().split())

for _ in range(Q):
    ans = 0
    sx, sy, sz, dx, dy, dz = map(int, input().split())
    vx = dx - sx
    vy = dy - sy
    vz = dz - sz
    for i in range(N):
        t = 0
        t += vx * (x[i] - sx)
        t += vy * (y[i] - sy)
        t += vz * (z[i] - sz)
        t /= vx**2 + vy**2 + vz**2
        len2 = 0
        len2 += (sx + vx * t - x[i])**2
        len2 += (sy + vy * t - y[i])**2
        len2 += (sz + vz * t - z[i])**2
        if 0 < t < 1 and len2 <= r[i]**2 + 1e-9:
            ans += l[i]
    print(ans)

```


p01893 Lost Graph

Problem statement

You and AOR Ika are preparing for a graph problem in competitive programming. Generating input cases is AOR Ika-chan's job. The input case for that problem is a directed graph of the $ N $ vertices. The vertices are numbered from $ 1 $ to $ N $. Edges may contain self-loops, but not multiple edges.

However, AOR Ika suddenly lost communication and couldn't get the original graph. All that remains is the following information:

* The number of vertices with degree $ i $ is $ a_i $. That is, the number of vertices ending in $ i $ is $ a_i $.
* The number of vertices with degree $ i $ is $ b_i $. That is, the number of vertices starting from $ i $ is $ b_i $.

Is there a directed graph that is consistent with the information left behind? Judge it, output YES if it exists, and then output one consistent directed graph. If there are more than one, any one may be output. If it does not exist, output NO.

Input constraints

$ 1 \ leq n \ leq 50 $
$ 0 \ leq a_i \ leq n $
$ 0 \ leq b_i \ leq n $

sample

Sample input 1

3
1 2 0 0
1 2 0 0

Sample output 1

YES YES
0 1 0
0 0 1
0 0 0

Sample input 2

1
Ten
Ten

Sample output 2

YES YES
0

Sample input 3

2
0 2 0
0 2 0

Sample output 3

YES YES
0 1
Ten

Sample input 4

Four
1 3 0 0 0
3 0 0 1 0

Sample output 4

YES YES
0 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0

Sample input 5

1
1 1
0 0

Sample output 5

NO

input

$ n $
$ a_0 \ cdots a_n $
$ b_0 \ cdots b_n $

output

If there is a graph that meets the conditions, output it in the following format. $ e_ {ij} $ should be 1 if there is a directed edge from $ i $ to $ j $, or 0 otherwise. Be careful not to print a blank at the end of the line.

YES YES
$ e_ {11} \ e_ {12} \ cdots e_ {1n} $
$ e_ {21} \ e_ {22} \ cdots e_ {2n} $
$ \ vdots $
$ e_ {n1} \ e_ {n2} \ cdots e_ {nn} $

If not, output as follows.

NO

Example

Input

3
1 2 0 0
1 2 0 0

Output

YES
0 1 0
0 0 1
0 0 0

```python
from operator import itemgetter
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
cnt_a = 0
cnt_b = 0
for i, (a, b) in enumerate(zip(A, B)):
    cnt_a += i*a
    cnt_b += i*b

if cnt_a!=cnt_b or not sum(A)==sum(B)==N:
    print("NO")
    exit()

B_ = []
cumi = 0
for i, b in enumerate(B):
    for j in range(b):
        B_.append([cumi, i])
        cumi += 1
B_.sort(key=itemgetter(1), reverse=True)

Ans = [[0]*N for _ in range(N)]
cumi = 0
for i, a in enumerate(A[1:], 1):
    if len(B_) < i:
        print("NO")
        exit()
    for k in range(a):
        for j in range(i):
            B_[j][1] -= 1
            if B_[j][1] < 0:
                print("NO")
                exit()
            Ans[B_[j][0]][cumi] = 1
        cumi += 1
        B_.sort(key=itemgetter(1), reverse=True)
print("YES")
for ans in Ans:
    print(*ans)

```


p02030 Information Search

A: Information Search

problem

The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example

* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7

And so on.

From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and if you search for or, ID 1, 2, 3, 4, 7, 9 will be hit.

Here, and search means "listing elements contained in either list", or search means "listing elements contained in at least one of the lists".

Since the posting list is given, output the results of and search and or search respectively.

Input format

n m
a_1 a_2 $ \ ldots $ a_n
b_1 b_2 $ \ ldots $ b_m

All inputs consist of integers.

The first line gives the lengths n and m of the two posting lists to search, separated by spaces.

The second and third lines are given the IDs contained in their respective posting lists, separated by blanks.

Constraint

* 1 \ leq n, m \ leq 2 \ times 10 ^ 5
* a_i <a_j (i <j)
* b_i <b_j (i <j)
* 1 \ leq a_i, b_i \ leq 10 ^ 9

Output format

Let A be the number of hits in the and search, and B be the number of hits in the or search.

Print on the first line in the order A B, separated by blanks.

Output the IDs hit by and search on the following line A in ascending order.

Output the IDs hit by or search on the following B line in ascending order.

Input example 1

4 4
1 2 4 9
1 3 4 7

Output example 1

2 6
1
Four
1
2
3
Four
7
9

Input example 2

4 4
1 3 5 7
2 4 6 8

Output example 2

0 8
1
2
3
Four
Five
6
7
8

Input example 3

3 5
one two Three
1 2 3 4 5

Output example 3

3 5
1
2
3
1
2
3
Four
Five

Example

Input

4 4
1 2 4 9
1 3 4 7

Output

2 6
1
4
1
2
3
4
7
9

```python
n,m = map(int,input().split())
a = set(map(int,input().split()))
b = set(map(int,input().split()))
i = sorted(a&b)
u = sorted(a|b)
print(len(i),len(u))
for x in i:
    print(x)
for x in u:
    print(x)

```


p02461 Map: Range Search

For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.

* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$.
* get($key$): Print the value with the specified $key$. Print 0 if there is no such element.
* delete($key$): Delete the element with the specified $key$.
* dump($L$, $R$): Print all elements formed by a pair of the key and the value such that the key is greater than or equal to $L$ and less than or equal to $R$ in lexicographic order.

Constraints

* $1 \leq q \leq 200,000$
* $1 \leq x \leq 1,000,000,000$
* $1 \leq $ length of $key$ $ \leq 20$
* $key$ consists of lower-case letters
* $L \leq R$ in lexicographic order
* The total number of elements printed by dump operations does not exceed $1,000,000$

Input

The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $key$ $x$

or

1 $key$

or

2 $key$

or

3 $L$ $R$

where the first digits 0, 1, 2 and 3 represent insert, get, delete and dump operations.

Output

For each get operation, print the corresponding value.
For each dump operation, print the corresponding elements formed by a pair of the key and the value. For the dump operation, print the elements (a pair of key and value separated by a space character) in ascending order of the keys.

Example

Input

9
0 blue 4
0 red 1
0 white 5
1 red
1 blue
2 red
1 black
1 red
3 w z

Output

1
4
0
0
white 5

```python
import sys
import bisect

n = int(input())
arr = []
lines = sys.stdin.readlines()
ans = [None] * n
d = {}
for i in range(n):
    q, *arg = lines[i].split()
    key = arg[0]
    idx = bisect.bisect_left(arr, arg[0])
    if q == '0':    # insert
        if idx == len(arr) or arr[idx] != key:
            arr.insert(idx, key)
        d[key] = arg[1]
    elif q == '1':  # get
        ans[i] = d[key] if idx != len(arr) and arr[idx] == key else '0'
    elif q == '2':  # delete
        if idx < len(arr) and arr[idx] == key:
            del arr[idx]
            del d[key]
    elif q == '3':  # dump L R
        r_idx = bisect.bisect_right(arr, arg[1])
        ans[i] = '\n'.join([f'{key_} {d[key_]}' for key_ in arr[idx:r_idx]]) if (r_idx - idx) != 0 else None

[print(x) for x in ans if x is not None]

```


1010_B. Rocket

This is an interactive problem.

Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.

Let's define x as the distance to Mars. Unfortunately, Natasha does not know x. But it is known that 1 ≤ x ≤ m, where Natasha knows the number m. Besides, x and m are positive integers.

Natasha can ask the rocket questions. Every question is an integer y (1 ≤ y ≤ m). The correct answer to the question is -1, if x<y, 0, if x=y, and 1, if x>y. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to t, then, if the rocket answers this question correctly, then it will answer t, otherwise it will answer -t.

In addition, the rocket has a sequence p of length n. Each element of the sequence is either 0 or 1. The rocket processes this sequence in the cyclic order, that is 1-st element, 2-nd, 3-rd, …, (n-1)-th, n-th, 1-st, 2-nd, 3-rd, …, (n-1)-th, n-th, …. If the current element is 1, the rocket answers correctly, if 0 — lies. Natasha doesn't know the sequence p, but she knows its length — n.

You can ask the rocket no more than 60 questions.

Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.

Your solution will not be accepted, if it does not receive an answer 0 from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).

Input

The first line contains two integers m and n (1 ≤ m ≤ 10^9, 1 ≤ n ≤ 30) — the maximum distance to Mars and the number of elements in the sequence p.

Interaction

You can ask the rocket no more than 60 questions.

To ask a question, print a number y (1≤ y≤ m) and an end-of-line character, then do the operation flush and read the answer to the question.

If the program reads 0, then the distance is correct and you must immediately terminate the program (for example, by calling exit(0)). If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.

If at some point your program reads -2 as an answer, it must immediately end (for example, by calling exit(0)). You will receive the "Wrong answer" verdict, and this will mean that the request is incorrect or the number of requests exceeds 60. If you ignore this, you can get any verdict, since your program will continue to read from the closed input stream.

If your program's request is not a valid integer between -2^{31} and 2^{31}-1 (inclusive) without leading zeros, then you can get any verdict.

You can get "Idleness limit exceeded" if you don't print anything or if you forget to flush the output.

To flush the output buffer you can use (after printing a query and end-of-line):

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

Hacking

Use the following format for hacking:

In the first line, print 3 integers m,n,x (1≤ x≤ m≤ 10^9, 1≤ n≤ 30) — the maximum distance to Mars, the number of elements in the sequence p and the current distance to Mars.

In the second line, enter n numbers, each of which is equal to 0 or 1 — sequence p.

The hacked solution will not have access to the number x and sequence p.

Example

Input

5 2
1
-1
-1
1
0

Output

1
2
4
5
3

Note

In the example, hacking would look like this:

5 2 3

1 0

This means that the current distance to Mars is equal to 3, Natasha knows that it does not exceed 5, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...

Really:

on the first query (1) the correct answer is 1, the rocket answered correctly: 1;

on the second query (2) the correct answer is 1, the rocket answered incorrectly: -1;

on the third query (4) the correct answer is -1, the rocket answered correctly: -1;

on the fourth query (5) the correct answer is -1, the rocket answered incorrectly: 1;

on the fifth query (3) the correct and incorrect answer is 0.

```python
from sys import stdin
from math import *
from sys import stdout

line = stdin.readline().rstrip().split()
m = int(line[0])
n = int(line[1])

bits = []
for i in range(n):
    print(m)
    stdout.flush()
    line = stdin.readline().rstrip().split()
    res = int(line[0])
    if res == 0:
        exit(0)
    if res == 1:
        bits.append(-1)
    else:
        bits.append(1)

minN = 1
maxN = m
i = 0
while True:
    current = int((minN + maxN) / 2)
    print(current)
    stdout.flush()
    line = stdin.readline().rstrip().split()
    res = int(line[0])
    if res == 0:
        exit(0)
    res *= bits[i]
    i = (i+1) % n
    if res == 1:
        minN = current + 1
    else:
        maxN = current - 1

```


1034_B. Little C Loves 3 II

Little C loves number «3» very much. He loves all things about it.

Now he is playing a game on a chessboard of size n × m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly 3. The Manhattan distance between two cells (x_i,y_i) and (x_j,y_j) is defined as |x_i-x_j|+|y_i-y_j|.

He want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place.

Input

A single line contains two integers n and m (1 ≤ n,m ≤ 10^9) — the number of rows and the number of columns of the chessboard.

Output

Print one integer — the maximum number of chessmen Little C can place.

Examples

Input

2 2

Output

0

Input

3 3

Output

8

Note

In the first example, the Manhattan distance between any two cells is smaller than 3, so the answer is 0.

In the second example, a possible solution is (1,1)(3,2), (1,2)(3,3), (2,1)(1,3), (3,1)(2,3).


109_B. Lucky Probability

Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl, pr] and Vasya chooses an integer v from the interval [vl, vr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v, p), max(v, p)] contains exactly k lucky numbers.

Input

The single line contains five integers pl, pr, vl, vr and k (1 ≤ pl ≤ pr ≤ 109, 1 ≤ vl ≤ vr ≤ 109, 1 ≤ k ≤ 1000).

Output

On the single line print the result with an absolute error of no more than 10 - 9.

Examples

Input

1 10 1 10 2

Output

0.320000000000

Input

5 6 8 10 1

Output

1.000000000000

Note

Consider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, <image>

In first case there are 32 suitable pairs: (1, 7), (1, 8), (1, 9), (1, 10), (2, 7), (2, 8), (2, 9), (2, 10), (3, 7), (3, 8), (3, 9), (3, 10), (4, 7), (4, 8), (4, 9), (4, 10), (7, 1), (7, 2), (7, 3), (7, 4), (8, 1), (8, 2), (8, 3), (8, 4), (9, 1), (9, 2), (9, 3), (9, 4), (10, 1), (10, 2), (10, 3), (10, 4). Total number of possible pairs is 10·10 = 100, so answer is 32 / 100.

In second case Petya always get number less than Vasya and the only lucky 7 is between this numbers, so there will be always 1 lucky number.

```python
import itertools as it

all_lucky = []

for length in range(1, 10):
    for comb in it.product(['7', '4'], repeat=length):
        all_lucky += [int(''.join(comb))]

all_lucky.sort()

# print(len(all_lucky))

pl, pr, vl, vr, k = map(int, input().split())

result = 0

def inters_len(a, b, c, d):
    a, b = sorted([a, b])
    c, d = sorted([c, d])
    return (max([a, c]), min([b, d]))

def check_for_intervals(pl, pr, vl, vr):
    global result
    for i in range(1, len(all_lucky) - k):
        le, re = i, i + k - 1

        a, b = inters_len(all_lucky[le - 1] + 1, all_lucky[le], pl, pr)
        left_len = max([0, b - a + 1])
        c, d = inters_len(all_lucky[re], all_lucky[re + 1] - 1, vl, vr)
        right_len = max([0, d - c + 1])

        result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

        if b == c and left_len * right_len > 1e-6:
            result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

    a, b = inters_len(0, all_lucky[0], pl, pr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[k - 1], all_lucky[k] - 1, vl, vr)
    right_len = max([0, d - c + 1])

    #print((left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1)))
    #print(left_len, right_len)
    result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

    a, b = inters_len(all_lucky[-(k + 1)] + 1, all_lucky[-k], pl, pr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[-1], 10**9, vl, vr)
    right_len = max([0, d - c + 1])

    #print((left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1)))
    result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

#print(all_lucky[:5])

if k != len(all_lucky):
    check_for_intervals(pl, pr, vl, vr)
    check_for_intervals(vl, vr, pl, pr)
else:
    a, b = inters_len(0, all_lucky[0], pl, pr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[-1], 10**9, vl, vr)
    right_len = max([0, d - c + 1])
    result += (left_len / (pr - pl + 1)) * (right_len / (vr - vl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

    a, b = inters_len(0, all_lucky[0], vl, vr)
    left_len = max([0, b - a + 1])
    c, d = inters_len(all_lucky[-1], 10**9, pl, pr)
    right_len = max([0, d - c + 1])
    result += (left_len / (vr - vl + 1)) * (right_len / (pr - pl + 1))

    if b == c and left_len * right_len > 1e-6:
        result -= (1 / (pr - pl + 1) / (vr - vl + 1)) / 2

print(result)

# Made By Mostafa_Khaled
```


1120_B. Once in a casino

One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.

A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits.

Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play.

Input

The first line contains a single integer n (2 ≤ n ≤ 10^5) standing for the length of numbers a and b.

The next two lines contain numbers a and b, each one on a separate line (10^{n-1} ≤ a, b < 10^n).

Output

If it is impossible to win the jackpot, print a single integer -1.

Otherwise, the first line must contain the minimal possible number c of coins the player has to spend.

min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1≤ d_i≤ n - 1, s_i = ± 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change).

Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them.

Examples

Input

3
223
322

Output

2
1 1
2 -1

Input

2
20
42

Output

2
1 1
1 1

Input

2
35
44

Output

-1

Note

In the first example, we can make a +1 operation on the two first digits, transforming number 223 into 333, and then make a -1 operation on the last two digits, transforming 333 into 322.

It's also possible to do these operations in reverse order, which makes another correct answer.

In the last example, one can show that it's impossible to transform 35 into 44.

```python
def main():
    n = int(input())
    a = list(map(int, (x for x in input())))
    b = list(map(int, (x for x in input())))
    x = [0] * (n - 1)
    x[0] = b[0] - a[0]
    for i in range(1, n - 1):
        x[i] = b[i] - a[i] - x[i - 1]
    if a[n - 1] + x[n - 2] != b[n - 1]:
        print(-1)
        return
    cnt = sum(map(abs, x))  # prevbug: ftl
    print(cnt)
    cnt = min(cnt, 10 ** 5)
    index = 0

    def handle_zero_nine(cur_zero):
        nonlocal cnt
        nxt = index + 1
        # cur_zero = True prevbug: preserved this line
        while True:
            if cur_zero and a[nxt + 1] != 9:
                break
            if not cur_zero and a[nxt + 1] != 0:
                break
            nxt += 1
            cur_zero = not cur_zero
        while nxt > index:
            if cnt == 0:
                break
            if cur_zero:
                print(nxt + 1, 1)
                a[nxt] += 1
                a[nxt + 1] += 1
            else:
                print(nxt + 1, -1)
                a[nxt] -= 1
                a[nxt + 1] -= 1
            nxt -= 1
            cnt -= 1
            # print(a)
            cur_zero = not cur_zero

    while cnt > 0:
        if a[index] == b[index]:
            index += 1
            continue
        elif a[index] > b[index] and a[index + 1] == 0:
            handle_zero_nine(True)
        elif a[index] < b[index] and a[index + 1] == 9:
            handle_zero_nine(False)
        elif a[index] > b[index]:
            print(index + 1, -1)
            a[index] -= 1
            a[index + 1] -= 1
            cnt -= 1
            # print(a)
        elif a[index] < b[index]:
            print(index + 1, 1)
            a[index] += 1
            a[index + 1] += 1
            cnt -= 1
            # print(a)

if __name__ == '__main__':
    main()

```


1187_B. Letters Shop

The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.

Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.

There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.

  * For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead").
  * For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead").
  * For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead").
  * For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead").
  * For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead").

It is guaranteed that every friend can construct her/his name using the letters from the string s.

Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.

Input

The first line contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of showcase string s.

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

The third line contains one integer m (1 ≤ m ≤ 5 ⋅ 10^4) — the number of friends.

The i-th of the next m lines contains t_i (1 ≤ |t_i| ≤ 2 ⋅ 10^5) — the name of the i-th friend.

It is guaranteed that ∑ _{i=1}^m |t_i| ≤ 2 ⋅ 10^5.

Output

For each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.

It is guaranteed that every friend can construct her/his name using the letters from the string s.

Example

Input

9
arrayhead
5
arya
harry
ray
r
areahydra

Output

5
6
5
2
9

```python
from collections import defaultdict

n = int(input())
s = input()
r = defaultdict(list)
for i, c in enumerate(s):
    r[c].append(i)
m = int(input())
for i in range(m):
    t = input()
    ans = 0
    pos = defaultdict(int)
    for c in t:
        pos[c] += 1
        ans = max(ans, r[c][pos[c]-1])
    print(ans+1)

```


1206_A. Choose Two Numbers

You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.

Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.

For example, if A = [2, 1, 7] and B = [1, 3, 4], we can choose 1 from A and 4 from B, as number 5 = 1 + 4 doesn't belong to A and doesn't belong to B. However, we can't choose 2 from A and 1 from B, as 3 = 2 + 1 belongs to B.

It can be shown that such a pair exists. If there are multiple answers, print any.

Choose and print any such two numbers.

Input

The first line contains one integer n (1≤ n ≤ 100) — the number of elements of A.

The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 200) — the elements of A.

The third line contains one integer m (1≤ m ≤ 100) — the number of elements of B.

The fourth line contains m different integers b_1, b_2, ..., b_m (1 ≤ b_i ≤ 200) — the elements of B.

It can be shown that the answer always exists.

Output

Output two numbers a and b such that a belongs to A, b belongs to B, but a+b doesn't belong to nor A neither B.

If there are multiple answers, print any.

Examples

Input

1
20
2
10 20

Output

20 20

Input

3
3 2 2
5
1 5 7 7 9

Output

3 1

Input

4
1 3 5 7
4
7 5 3 1

Output

1 1

Note

In the first example, we can choose 20 from array [20] and 20 from array [10, 20]. Number 40 = 20 + 20 doesn't belong to any of those arrays. However, it is possible to choose 10 from the second array too.

In the second example, we can choose 3 from array [3, 2, 2] and 1 from array [1, 5, 7, 7, 9]. Number 4 = 3 + 1 doesn't belong to any of those arrays.

In the third example, we can choose 1 from array [1, 3, 5, 7] and 1 from array [7, 5, 3, 1]. Number 2 = 1 + 1 doesn't belong to any of those arrays.

```python
n=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
t=[];o=[]
for i in a:
    for j in b:
        t.append(i+j)
        o.append((i,j))

for i in range(len(t)):
    if (t[i] not in a) and (t[i] not in b):
        print(o[t.index(t[i])][0])
        print(o[t.index(t[i])][1])
        break;

```


1223_D. Sequence Sorting

You are given a sequence a_1, a_2, ..., a_n, consisting of integers.

You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.

For example, if a = [2, 1, 3, 1, 1, 3, 2], you can get the following sequences in one operation (for convenience, denote elements equal to x as x-elements):

  * [1, 1, 1, 2, 3, 3, 2] if you move all 1-elements to the beginning;
  * [2, 3, 3, 2, 1, 1, 1] if you move all 1-elements to the end;
  * [2, 2, 1, 3, 1, 1, 3] if you move all 2-elements to the beginning;
  * [1, 3, 1, 1, 3, 2, 2] if you move all 2-elements to the end;
  * [3, 3, 2, 1, 1, 1, 2] if you move all 3-elements to the beginning;
  * [2, 1, 1, 1, 2, 3, 3] if you move all 3-elements to the end;

You have to determine the minimum number of such operations so that the sequence a becomes sorted in non-descending order. Non-descending order means that for all i from 2 to n, the condition a_{i-1} ≤ a_i is satisfied.

Note that you have to answer q independent queries.

Input

The first line contains one integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of the queries. Each query is represented by two consecutive lines.

The first line of each query contains one integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements.

The second line of each query contains n integers a_1, a_2, ... , a_n (1 ≤ a_i ≤ n) — the elements.

It is guaranteed that the sum of all n does not exceed 3 ⋅ 10^5.

Output

For each query print one integer — the minimum number of operation for sorting sequence a in non-descending order.

Example

Input

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

Output

2
0
1

Note

In the first query, you can move all 1-elements to the beginning (after that sequence turn into [1, 1, 1, 3, 6, 6, 3]) and then move all 6-elements to the end.

In the second query, the sequence is sorted initially, so the answer is zero.

In the third query, you have to move all 2-elements to the beginning.

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

for _ in range(int(input())):
    n=int(input())
    a=list(map(int,input().split()))
    stored=[-1 for i in range(n+2)]
    counted=[[0,0] for i in range(n+2)]
    count=0
    for i in range(n):
        stored[a[i]]=a[i]
        if(counted[a[i]][0]==0):
            count+=1
        counted[a[i]][0]+=1
        counted[a[i]][1]+=1
    pt=n+1
    p_pt=0
    for i in range(n+1,-1,-1):
        if(stored[i]>=0):
            p_pt=pt
            pt=stored[i]
            stored[i]=p_pt
        else:
            stored[i]=pt
    ans=[0 for i in range(n+2)]
    for i in range(n):
        counted[a[i]][1] -= 1
        if(counted[stored[a[i]]][0]-counted[stored[a[i]]][1]==0 and counted[a[i]][1]==0):
            ans[stored[a[i]]]=ans[a[i]]+1
    maxi=max(max(ans[:n+1])+1,ans[-1])
    print(count-maxi)
```


1249_A. Yet Another Dividing into Teams

You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that:

  * No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than 1);
  * the number of teams is the minimum possible.

You have to answer q independent queries.

Input

The first line of the input contains one integer q (1 ≤ q ≤ 100) — the number of queries. Then q queries follow.

The first line of the query contains one integer n (1 ≤ n ≤ 100) — the number of students in the query. The second line of the query contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100, all a_i are distinct), where a_i is the programming skill of the i-th student.

Output

For each query, print the answer on it — the minimum number of teams you can form if no two students i and j such that |a_i - a_j| = 1 may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than 1)

Example

Input

4
4
2 10 1 20
2
3 6
5
2 3 4 99 100
1
42

Output

2
1
2
1

Note

In the first query of the example, there are n=4 students with the skills a=[2, 10, 1, 20]. There is only one restriction here: the 1-st and the 3-th students can't be in the same team (because of |a_1 - a_3|=|2-1|=1). It is possible to divide them into 2 teams: for example, students 1, 2 and 4 are in the first team and the student 3 in the second team.

In the second query of the example, there are n=2 students with the skills a=[3, 6]. It is possible to compose just a single team containing both students.

```python
from itertools import *

q = int(input())

for _ in range(q):
    n = int(input())
    a = list(map(int, input().split()))

    a.sort()

    cnt = 1
    while len(a) > 1:
        a = list(a)
        b = []
        for i in range(1, len(a)):
            if a[i] - a[i - 1] <= 1:
                b.append(a[i])

        if not b:
            break
        else:
            cnt += 1

        a = set(a) - set(b)

    print(cnt)

```