1440_C1. Binary Table (Easy Version)

This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.

You are given a binary table of size n × m. This table consists of symbols 0 and 1.

You can make such operation: select 3 different cells that belong to one 2 × 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).

Your task is to make all symbols in the table equal to 0. You are allowed to make at most 3nm operations. You don't need to minimize the number of operations.

It can be proved that it is always possible.

Input

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

The first line of the description of each test case contains two integers n, m (2 ≤ n, m ≤ 100).

Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.

It is guaranteed that the sum of nm for all test cases does not exceed 20000.

Output

For each test case print the integer k (0 ≤ k ≤ 3nm) — the number of operations.

In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≤ x_1, x_2, x_3 ≤ n, 1 ≤ y_1, y_2, y_3 ≤ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong into some 2 × 2 square.

Example

Input

5
2 2
10
11
3 3
011
101
110
4 4
1111
0110
0110
1111
5 5
01011
11001
00010
11011
10000
2 3
011
101

Output

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

Note

In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.

In the second test case:

  * operation with cells (2, 1), (3, 1), (3, 2). After it the table will be:

    011
    001
    000

  * operation with cells (1, 2), (1, 3), (2, 3). After it the table will be:

    000
    000
    000

In the fifth test case:

  * operation with cells (1, 3), (2, 2), (2, 3). After it the table will be:

    010
    110

  * operation with cells (1, 2), (2, 1), (2, 2). After it the table will be:

    000
    000

```python
import sys
from itertools import permutations
from itertools import combinations
from itertools import combinations_with_replacement
#sys.stdin = open('/Users/pranjalkandhari/Desktop/Template/input.txt', 'r')

def makeThree(mat , i , j , liAns):
    liToAdd = []
    if(mat[i][j] == 1):
        liToAdd.append(i)
        liToAdd.append(j)
        mat[i][j] = 0

    if(mat[i+1][j] == 1):
        liToAdd.append(i+1)
        liToAdd.append(j)
        mat[i+1][j] = 0

    if(mat[i][j+1] == 1):
        liToAdd.append(i)
        liToAdd.append(j+1)
        mat[i][j+1] = 0

    if(mat[i+1][j+1] == 1):
        liToAdd.append(i+1)
        liToAdd.append(j+1)
        mat[i+1][j+1] = 0

    liAns.append(liToAdd)

def makeTwo(mat , i , j , liAns):
    liToAdd = []
    liAllCoord = [(i,j) , (i+1,j) , (i,j+1) , (i+1,j+1)]
    flag = 0
    for coord in liAllCoord:
        #print(mat[coord[0]][coord[1]])
        if(mat[coord[0]][coord[1]] == 1 and flag == 0):
            flag = 1
            liToAdd.append(coord[0])
            liToAdd.append(coord[1])

        if(mat[coord[0]][coord[1]] == 0):
            liToAdd.append(coord[0])
            liToAdd.append(coord[1])
    a = 0
    #print('makeTwo' , liToAdd)
    while(a<6):
        #print('46 A' , a)
        initial = mat[liToAdd[a]][liToAdd[a+1]]
        if(initial == 1):
            mat[liToAdd[a]][liToAdd[a+1]] = 0
        else:
            mat[liToAdd[a]][liToAdd[a+1]] = 1
        a+=2

    liAns.append(liToAdd)
    makeThree(mat , i , j , liAns)

def makeOne(mat , i , j , liAns):
    liToAdd = []
    liAllCoord = [(i,j) , (i+1,j) , (i,j+1) , (i+1,j+1)]
    ctr = 0
    for coord in liAllCoord:
        if(mat[coord[0]][coord[1]] == 1):
            liToAdd.append(coord[0])
            liToAdd.append(coord[1])
        if(mat[coord[0]][coord[1]] == 0 and ctr<2):
            ctr += 1
            liToAdd.append(coord[0])
            liToAdd.append(coord[1])
    a = 0
    while(a<6):
        initial = mat[liToAdd[a]][liToAdd[a+1]]
        if(initial == 1):
            mat[liToAdd[a]][liToAdd[a+1]] = 0
        else:
            mat[liToAdd[a]][liToAdd[a+1]] = 1
        a+=2

    liAns.append(liToAdd)
    makeTwo(mat , i , j , liAns)

def makeFour(mat , i , j , liAns):
    liAllCoord = [(i,j) , (i+1,j) , (i,j+1) , (i+1,j+1)]
    ctr = 0
    liToAdd = []
    for coord in liAllCoord:
        if(ctr>=3):
            break
        ctr += 1
        liToAdd.append(coord[0])
        liToAdd.append(coord[1])
        mat[coord[0]][coord[1]] = 0
    liAns.append(liToAdd)
    makeOne(mat , i , j , liAns)

for _ in range( int(input()) ):
    liStr = input().split()
    p = int(liStr[0])
    q = int(liStr[1])

    mat = [] #Matrix of size pXq
    for _ in range(0,p):
        liStr = list(input())
        li = []
        for i in liStr:
            li.append(int(i))
        mat.append(li)

    #print(mat)

    liAns = [] #List of tuple of 6 elements.

    i = 0
    while(i<p):
        j = 0
        while(j<q):

            if(i == (p-1)):
                i = i-1
            if(j == (q-1)):
                j = j-1

            ctr = 0
            if(mat[i][j] == 1):
                ctr += 1
            if(mat[i+1][j] == 1):
                ctr += 1
            if(mat[i][j+1] == 1):
                ctr += 1
            if(mat[i+1][j+1] == 1):
                ctr += 1

            if(ctr == 1):
                makeOne(mat , i , j , liAns)
            if(ctr == 2):
                makeTwo(mat , i , j , liAns)
            if(ctr == 3):
                makeThree(mat , i , j , liAns)
            if(ctr == 4):
                makeFour(mat , i , j , liAns)

            j += 2
        i += 2
    print(len(liAns))
    for sixNum in liAns:
        for a in sixNum:
            print(a+1 , end = ' ')
        print()
```


1467_D. Sum of Paths

There are n cells, numbered 1,2,..., n from left to right. You have to place a robot at any cell initially. The robot must make exactly k moves.

In one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell i, it must move to either the cell i-1 or the cell i+1, as long as it lies between 1 and n (endpoints inclusive). The cells, in the order they are visited (including the cell the robot is placed), together make a good path.

Each cell i has a value a_i associated with it. Let c_0, c_1, ..., c_k be the sequence of cells in a good path in the order they are visited (c_0 is the cell robot is initially placed, c_1 is the cell where the robot is after its first move, and so on; more formally, c_i is the cell that the robot is at after i moves). Then the value of the path is calculated as a_{c_0} + a_{c_1} + ... + a_{c_k}.

Your task is to calculate the sum of values over all possible good paths. Since this number can be very large, output it modulo 10^9 + 7. Two good paths are considered different if the starting cell differs or there exists an integer i ∈ [1, k] such that the current cell of the robot after exactly i moves is different in those paths.

You must process q updates to a and print the updated sum each time. Each update changes the value of exactly one cell. See the input format and the sample input-output for more details.

Input

The first line of the input contains three space-separated integers n, k and q (2 ≤ n ≤ 5000; 1 ≤ k ≤ 5000; 1 ≤ q ≤ 2 ⋅ 10^5).

The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).

q lines follow. Each line contains two space-separated integers i and x (1 ≤ i ≤ n; 1 ≤ x ≤ 10^9) indicating that you must change the value of a_i to x.

Output

Print q integers. The i-th integer should be the sum of values over all good paths after the first i updates are performed. Since the answers may be large, print them modulo 10^9 + 7.

Examples

Input

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

Output

62
58
78
86
86

Input

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

Output

157
147
207
227
227

Input

4 40 6
92 21 82 46
3 56
1 72
4 28
1 97
2 49
2 88

Output

239185261
666314041
50729936
516818968
766409450
756910476

Note

In the first example, the good paths are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), (4, 3), (4, 5), (5, 4).

Initially the values of a are [3, 5, 1, 4, 2]. After the first update, they become [9, 5, 1, 4, 2]. After the second update, they become [9, 4, 1, 4, 2], and so on.

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

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

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

dp = [[0]*(k+1) for i in range(n+2)]
mod = 10**9 + 7

for i in range(1,n+1):
    dp[i][0] = 1
for j in range(1, k+1):
    for i in range(1, n+1):
        dp[i][j] = (dp[i-1][j-1] + dp[i+1][j-1]) % mod

c = [0]*n
for i in range(1, n+1):
    for pos in range(k+1):
        c[i-1] += dp[i][pos] * dp[i][-pos-1]
        c[i-1] %= mod

total = sum((a[i]*c[i]) % mod for i in range(n)) % mod

for _ in range(q):
    i, x = map(int, input().split())
    diff = a[i-1] - x
    a[i-1] = x
    total = (total - diff*c[i-1]) % mod
    print(total)
```


1491_G. Switch and Flip

There are n coins labeled from 1 to n. Initially, coin c_i is on position i and is facing upwards ((c_1, c_2, ..., c_n) is a permutation of numbers from 1 to n). You can do some operations on these coins.

In one operation, you can do the following:

  * Choose 2 distinct indices i and j.

  * Then, swap the coins on positions i and j.

  * Then, flip both coins on positions i and j. (If they are initially faced up, they will be faced down after the operation and vice versa)

Construct a sequence of at most n+1 operations such that after performing all these operations the coin i will be on position i at the end, facing up.

Note that you do not need to minimize the number of operations.

Input

The first line contains an integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the number of coins.

The second line contains n integers c_1,c_2,...,c_n (1 ≤ c_i ≤ n, c_i ≠ c_j for i≠ j).

Output

In the first line, output an integer q (0 ≤ q ≤ n+1) — the number of operations you used.

In the following q lines, output two integers i and j (1 ≤ i, j ≤ n, i ≠ j) — the positions you chose for the current operation.

Examples

Input

3
2 1 3

Output

3
1 3
3 2
3 1

Input

5
1 2 3 4 5

Output

0

Note

Let coin i facing upwards be denoted as i and coin i facing downwards be denoted as -i.

The series of moves performed in the first sample changes the coins as such:

  * [~~~2,~~~1,~~~3]
  * [-3,~~~1,-2]
  * [-3,~~~2,-1]
  * [~~~1,~~~2,~~~3]

In the second sample, the coins are already in their correct positions so there is no need to swap.

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

n = int(input());A = [0] + list(map(int, input().split()));seen = [0] * (n + 1);cycles = [];ans = []
for i in range(1, n + 1):
    cur = [];j = i
    while not seen[j]:cur.append(j);seen[j] = 1;j = A[j]
    if len(cur) > 1: cycles.append(cur)
def swap(x, y):A[x], A[y] = A[y], A[x];ans.append((x, y))
for i in range(1, len(cycles), 2):
    X, Y = cycles[i - 1], cycles[i];swap(X[0], Y[0])
    for x in X[1:]: swap(x, Y[0])
    for y in Y[1:]: swap(y, X[0])
    swap(X[0], Y[0])
if len(cycles) % 2:
    X = cycles[-1]
    if len(X) > 2:
        for x in X[:-2]: swap(x, X[-1])
        swap(X[0], X[-2]);swap(X[-2], X[-1]);swap(X[0], X[-1])
    else:
        Y = []
        for i in range(1, n + 1):
            if i != X[0] and i != X[1]: break
        swap(i, X[0]);swap(i, X[1]);swap(i, X[0])
print(len(ans))
for a in ans: print(*a)
```


1514_D. Cut and Stick

Baby Ehab has a piece of Cut and Stick with an array a of length n written on it. He plans to grab a pair of scissors and do the following to it:

  * pick a range (l, r) and cut out every element a_l, a_{l + 1}, ..., a_r in this range;
  * stick some of the elements together in the same order they were in the array;
  * end up with multiple pieces, where every piece contains some of the elements and every element belongs to some piece.

More formally, he partitions the sequence a_l, a_{l + 1}, ..., a_r into subsequences. He thinks a partitioning is beautiful if for every piece (subsequence) it holds that, if it has length x, then no value occurs strictly more than ⌈ x/2 ⌉ times in it.

He didn't pick a range yet, so he's wondering: for q ranges (l, r), what is the minimum number of pieces he needs to partition the elements a_l, a_{l + 1}, ..., a_r into so that the partitioning is beautiful.

A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly zero) elements. Note that it does not have to be contiguous.

Input

The first line contains two integers n and q (1 ≤ n,q ≤ 3 ⋅ 10^5) — the length of the array a and the number of queries.

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

Each of the next q lines contains two integers l and r (1 ≤ l ≤ r ≤ n) — the range of this query.

Output

For each query, print the minimum number of subsequences you need to partition this range into so that the partitioning is beautiful. We can prove such partitioning always exists.

Example

Input

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

Output

1
2

Note

In the first query, you can just put the whole array in one subsequence, since its length is 6, and no value occurs more than 3 times in it.

In the second query, the elements of the query range are [3,2,3,3]. You can't put them all in one subsequence, since its length is 4, and 3 occurs more than 2 times. However, you can partition it into two subsequences: [3] and [2,3,3].

```python
from bisect import bisect, bisect_left
from random import random
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, q = map(int, input().split())
a = list(map(int, input().split()))
v = [list() for i in range(n + 1)]
for i in range(n):
  v[a[i]].append(i)
for i in range(q):
  l, r = map(int, input().split())
  l -= 1
  r -= 1
  ans = 1
  s = set()
  for j in range(25):
    idx = int(random() * (r - l + 1)) + l
    if a[idx] in s:
      continue
    s.add(a[idx])
    if len(v[a[idx]]) <= (r - l + 2) // 2:
      continue
    left = bisect_left(v[a[idx]], l)
    right = bisect(v[a[idx]], r)
    if right - left > (r - l + 2) // 2:
      ans = 2 * (right - left) - (r - l + 1)
      break
  print(ans)
```


1541_D. Tree Array

You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.

Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.

After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked nodes with at least one edge to a marked node.

It can be shown that the process marks all nodes in the tree.

The final array a is the list of the nodes' labels in order of the time each node was marked.

Find the expected number of inversions in the array that is generated by the tree and the aforementioned process.

The number of inversions in an array a is the number of pairs of indices (i, j) such that i < j and a_i > a_j. For example, the array [4, 1, 3, 2] contains 4 inversions: (1, 2), (1, 3), (1, 4), (3, 4).

Input

The first line contains a single integer n (2 ≤ n ≤ 200) — the number of nodes in the tree.

The next n - 1 lines each contains two integers x and y (1 ≤ x, y ≤ n; x ≠ y), denoting an edge between node x and y.

It's guaranteed that the given edges form a tree.

Output

Output the expected number of inversions in the generated array modulo 10^9+7.

Formally, let M = 10^9+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q not ≡ 0 \pmod{M}. Output the integer equal to p ⋅ q^{-1} mod M. In other words, output such an integer x that 0 ≤ x < M and x ⋅ q ≡ p \pmod{M}.

Examples

Input

3
1 2
1 3

Output

166666669

Input

6
2 1
2 3
6 1
1 4
2 5

Output

500000009

Input

5
1 2
1 3
1 4
2 5

Output

500000007

Note

This is the tree from the first sample:

<image>

For the first sample, the arrays are almost fixed. If node 2 is chosen initially, then the only possible array is [2, 1, 3] (1 inversion). If node 3 is chosen initially, then the only possible array is [3, 1, 2] (2 inversions). If node 1 is chosen initially, the arrays [1, 2, 3] (0 inversions) and [1, 3, 2] (1 inversion) are the only possibilities and equiprobable. In total, the expected number of inversions is 1/3⋅ 1 + 1/3 ⋅ 2 + 1/3 ⋅ (1/2 ⋅ 0 + 1/2 ⋅ 1) = 7/6.

166666669 ⋅ 6 = 7 \pmod {10^9 + 7}, so the answer is 166666669.

This is the tree from the second sample:

<image>

This is the tree from the third sample:

<image>

```python
from functools import lru_cache
from collections import deque

M = 10 ** 9 + 7

@lru_cache(None)
def inv(x):
    return pow(x, M - 2, M)

@lru_cache(None)
def dp(u, v):
    # u before v
    if u == 0:
        return 0
    if v == 0:
        return 1
    return (dp(u - 1, v) * inv(2) + dp(u, v - 1) * inv(2)) % M

def calc(n, link, start):
    res = 0
    for u in range(1, n + 1):
        for v in range(u + 1, n + 1):
            lca = (link[start][u] + link[start][v] - link[u][v]) // 2
            res += dp(link[start][u] - lca, link[start][v] - lca)
            res %= M
    return res

def main():
    n = int(input())
    graph = [[] for i in range(n + 1)]
    ans = 0
    for _ in range(n - 1):
        u, v = [int(word) for word in input().split()]
        graph[u].append(v)
        graph[v].append(u)
    link = [[-1 for j in range(n + 1)] for i in range(n + 1)]
    for i in range(1, n + 1):
        link[i][i] = 0
        q = deque()
        q.append(i)
        while len(q) != 0:
            u = q.popleft()
            for v in graph[u]:
                if link[i][v] >= 0:
                    continue
                link[i][v] = link[i][u] + 1
                q.append(v)
    for root in range(1, n + 1):
        ans += calc(n, link, start=root)
        ans %= M
    ans *= inv(n)
    ans %= M
    print(ans)

if __name__ == "__main__":
    main()

```


18_A. Triangle

At a geometry lesson Bob learnt that a triangle is called right-angled if it is nondegenerate and one of its angles is right. Bob decided to draw such a triangle immediately: on a sheet of paper he drew three points with integer coordinates, and joined them with segments of straight lines, then he showed the triangle to Peter. Peter said that Bob's triangle is not right-angled, but is almost right-angled: the triangle itself is not right-angled, but it is possible to move one of the points exactly by distance 1 so, that all the coordinates remain integer, and the triangle become right-angled. Bob asks you to help him and find out if Peter tricks him. By the given coordinates of the triangle you should find out if it is right-angled, almost right-angled, or neither of these.

Input

The first input line contains 6 space-separated integers x1, y1, x2, y2, x3, y3 — coordinates of the triangle's vertices. All the coordinates are integer and don't exceed 100 in absolute value. It's guaranteed that the triangle is nondegenerate, i.e. its total area is not zero.

Output

If the given triangle is right-angled, output RIGHT, if it is almost right-angled, output ALMOST, and if it is neither of these, output NEITHER.

Examples

Input

0 0 2 0 0 1

Output

RIGHT

Input

2 3 4 5 6 6

Output

NEITHER

Input

-1 0 2 0 0 1

Output

ALMOST

```python
import math
"""
#include <cstdio>
#include <iostream>
#include <algorithm>

bool isRight(int *c){

    int sides[3] = {0};
    sides[0] = (c[4] - c[2]) * (c[4] - c[2]) + (c[5] - c[3])* (c[5] - c[3]);
    sides[1] = (c[4] - c[0]) * (c[4] - c[0]) + (c[5] - c[1])* (c[5] - c[1]);
    sides[2] = (c[2] - c[0]) * (c[2] - c[0]) + (c[3] - c[1])* (c[3] - c[1]);

    std::sort(sides, sides + 3);
    if(sides[0] > 0 && sides[2] == sides[0] + sides[1]){return 1;}
    else{return 0;}
}

int main(){

    int points[6] = {0};
    for(int k = 0; k < 6; k++){scanf("%d", points + k);}

    std::string output = "NEITHER";
    if(isRight(points)){output = "RIGHT";}
    else{
        for(int k = 0; k < 6; k++){
            ++points[k];    if(isRight(points)){output = "ALMOST"; break;}
            points[k] -= 2; if(isRight(points)){output = "ALMOST"; break;}
            ++points[k];
        }
    }

    std::cout << output << std::endl;
    return 0;
}
"""
def distancia_euclidiana(x, y):
    lados = []
    lados.append(math.pow(x[0] - x[1], 2) + math.pow(y[0] - y[1], 2))
    lados.append(math.pow(x[0] - x[2], 2) + math.pow(y[0] - y[2], 2))
    lados.append(math.pow(x[1] - x[2], 2) + math.pow(y[1] - y[2], 2))
    return sorted(lados)

def is_right(pontos):
    distancias = distancia_euclidiana((pontos[0], pontos[2], pontos[4]), (pontos[1], pontos[3], pontos[5]))
    #return math.pow(distancias[2], 2) == math.pow(distancias[0], 2) + math.pow(distancias[1], 2)
    return distancias[0] > 0 and distancias[2] == distancias[1] + distancias[0]

pontos = [int(i) for i in input().split()]

resultado = 'NEITHER'

if is_right(pontos):
    resultado = 'RIGHT'
else:
    for i in range(0, 6):
        pontos[i] += 1
        if is_right(pontos):
            resultado = 'ALMOST'
            break
        pontos[i] -= 2
        if is_right(pontos):
            resultado = 'ALMOST'
            break
        pontos[i] += 1

print(resultado)

```


213_A. Game

Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies.

Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions:

  * Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer.
  * Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that.
  * Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that.
  * Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that.
  * Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that.
  * Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that.
  * Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that.

Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.

Input

The first line contains integer n (1 ≤ n ≤ 200) — the number of game parts. The next line contains n integers, the i-th integer — ci (1 ≤ ci ≤ 3) represents the number of the computer, on which you can complete the game part number i.

Next n lines contain descriptions of game parts. The i-th line first contains integer ki (0 ≤ ki ≤ n - 1), then ki distinct integers ai, j (1 ≤ ai, j ≤ n; ai, j ≠ i) — the numbers of parts to complete before part i.

Numbers on all lines are separated by single spaces. You can assume that the parts of the game are numbered from 1 to n in some way. It is guaranteed that there are no cyclic dependencies between the parts of the game.

Output

On a single line print the answer to the problem.

Examples

Input

1
1
0

Output

1

Input

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

Output

7

Note

Note to the second sample: before the beginning of the game the best strategy is to stand by the third computer. First we complete part 5. Then we go to the 1-st computer and complete parts 3 and 4. Then we go to the 2-nd computer and complete parts 1 and 2. In total we get 1+1+2+1+2, which equals 7 hours.

```python
n = int(input())
c = list(map(int, input().split()))
d = dict()
d[1] = []
d[2] = []
d[3] = []
for i in range(n):
    d[c[i]].append(i)
done = set()
mas = []
k = 0
poss = set()
for i in range(n):
    l = list(map(int, input().split()))
    l = l[1:]
    mas.append(l)
    if len(l) == 0:
        k = c[i]
        poss.add((k, i))
o = 0
bigans = 1000000000
for a in poss:
    k = a[0]
    done = set()
    done.add(a[1] + 1)
    ans = 1
    while len(done) != n:
        #o += 1
        if o == 10:
            break
        while True:
            y = len(done)
            for i in d[k]:
                if (i + 1) in done:
                    continue
                flag = True
                for j in mas[i]:
                    if j not in done:
                        flag = False
                if flag:
                    done.add(i + 1)
                    ans += 1
            if y == len(done):
                break
        if len(done) == n:
            break
        k += 1
        ans += 1
        if k == 4:
            k = 1
    bigans = min(bigans, ans)
print(bigans)

```


237_A. Free Cash

Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.

Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.

Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.

Input

The first line contains a single integer n (1 ≤ n ≤ 105), that is the number of cafe visitors.

Each of the following n lines has two space-separated integers hi and mi (0 ≤ hi ≤ 23; 0 ≤ mi ≤ 59), representing the time when the i-th person comes into the cafe.

Note that the time is given in the chronological order. All time is given within one 24-hour period.

Output

Print a single integer — the minimum number of cashes, needed to serve all clients next day.

Examples

Input

4
8 0
8 10
8 10
8 45

Output

2

Input

3
0 12
10 11
22 22

Output

1

Note

In the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.

In the second sample all visitors will come in different times, so it will be enough one cash.

```python
t=int(input())
d={}
while (t>0):
    t=t-1
    s=input()
    if s in d:
        d[s]+=1
    else:
        d[s]=1
print(max(d.values()))
```


285_D. Permutation Sum

Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.

Petya decided to introduce the sum operation on the set of permutations of length n. Let's assume that we are given two permutations of length n: a1, a2, ..., an and b1, b2, ..., bn. Petya calls the sum of permutations a and b such permutation c of length n, where ci = ((ai - 1 + bi - 1) mod n) + 1 (1 ≤ i ≤ n).

Operation <image> means taking the remainder after dividing number x by number y.

Obviously, not for all permutations a and b exists permutation c that is sum of a and b. That's why Petya got sad and asked you to do the following: given n, count the number of such pairs of permutations a and b of length n, that exists permutation c that is sum of a and b. The pair of permutations x, y (x ≠ y) and the pair of permutations y, x are considered distinct pairs.

As the answer can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).

Input

The single line contains integer n (1 ≤ n ≤ 16).

Output

In the single line print a single non-negative integer — the number of such pairs of permutations a and b, that exists permutation c that is sum of a and b, modulo 1000000007 (109 + 7).

Examples

Input

3

Output

18

Input

5

Output

1800


333_B. Chips

Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases:

  * At least one of the chips at least once fell to the banned cell.
  * At least once two chips were on the same cell.
  * At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row).

In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.

Input

The first line contains two space-separated integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 105) — the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 ≤ xi, yi ≤ n) — the coordinates of the i-th banned cell. All given cells are distinct.

Consider the field rows numbered from top to bottom from 1 to n, and the columns — from left to right from 1 to n.

Output

Print a single integer — the maximum points Gerald can earn in this game.

Examples

Input

3 1
2 2

Output

0

Input

3 0

Output

1

Input

4 3
3 1
3 2
3 3

Output

1

Note

In the first test the answer equals zero as we can't put chips into the corner cells.

In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.

In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).

```python
n, m = tuple(map(int, input().split(' ')))
vb = set()
hb = set()
for k in range(m):
	i, j = tuple(map(int, input().split(' ')))
	hb.add(i-1)
	vb.add(j-1)
c = 0
for i in range(1, n//2):
	c += 1 if i not in hb else 0
	c += 1 if n-i-1 not in hb else 0
	c += 1 if i not in vb else 0
	c += 1 if n-i-1 not in vb else 0
c += 1 if n%2==1 and (n//2 not in hb or n//2 not in vb) else 0
print(c)

```


37_A. Towers

Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.

Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.

Input

The first line contains an integer N (1 ≤ N ≤ 1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000.

Output

In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars.

Examples

Input

3
1 2 3

Output

1 3

Input

4
6 5 6 7

Output

2 3

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

a=list(set(l))
l.sort()
maxx=l.count(0)
for i in range(len(l)):
    if(l.count(l[i])>maxx):
        maxx=l.count(l[i])
print(maxx,len(a))

```


3_D. Least Cost Bracket Sequence

This is yet another problem on regular bracket sequences.

A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.

For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

Input

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Output

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second.

Print -1, if there is no answer. If the answer is not unique, print any of them.

Examples

Input

(??)
1 2
2 8

Output

4
()()

```python
from heapq import heappush, heappop
from sys import stdin, exit

template = list(next(stdin).strip())

n, cost, balance = len(template), 0, 0

min_heap = []

for i in range(n):
	if template[i] == '(':
		balance += 1
	elif template[i] == ')':
		balance -= 1
	else:
		cost_left, cost_right = map(int, next(stdin).split())
		template[i] = ')'
		cost += cost_right
		balance -= 1
		heappush(min_heap, (cost_left - cost_right, i))
	if balance < 0:
		if not min_heap:
			print(-1)
			exit(0)
		change_cost, index = heappop(min_heap)
		template[index] = '('
		cost += change_cost
		balance += 2

if balance == 0:
	print(cost)
	print(''.join(template))
else:
	print(-1)

```


427_A. Police Recruits

The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.

Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.

If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.

Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

Input

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers.

If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

Output

Print a single integer, the number of crimes which will go untreated.

Examples

Input

3
-1 -1 1

Output

2

Input

8
1 -1 1 -1 -1 1 1 1

Output

1

Input

11
-1 -1 2 -1 -1 -1 -1 -1 -1 -1 -1

Output

8

Note

Lets consider the second example:

  1. Firstly one person is hired.
  2. Then crime appears, the last hired person will investigate this crime.
  3. One more person is hired.
  4. One more crime appears, the last hired person will investigate this crime.
  5. Crime appears. There is no free policeman at the time, so this crime will go untreated.
  6. One more person is hired.
  7. One more person is hired.
  8. One more person is hired.

The answer is one, as one crime (on step 5) will go untreated.

```python
n=int(input())
a=list(map(int,input().split()))
oc=0
cc=0
ans=0
for i in a:
    if i>0:
        oc+=i
    elif oc==0:
        ans+=1
    else:
        oc-=1
print(ans)
```


44_I. Toys

Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her n toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile.

Input

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

Output

In the first line print the number of different variants of arrangement of toys into piles. Then print all the ways of arranging toys into piles in the order in which Sasha should try them (i.e. every next way must result from the previous one through the operation described in the statement). Every way should be printed in the following format. In every pile the toys should be arranged in ascending order of the numbers. Then the piles should be sorted in ascending order of the numbers of the first toys there. Output every way on a single line. Cf. the example to specify the output data format. If the solution is not unique, output any of them.

Examples

Input

3

Output

5
{1,2,3}
{1,2},{3}
{1},{2,3}
{1},{2},{3}
{1,3},{2}

```python
def combinacoes(x):
    # Se for apenas 1 elemento retorna 1 arranjo
    if x == 1:
        return [[0]]
    else:
        # Adiciona os elementos a lista auxiliar
        aux = combinacoes(x - 1)
    pilha = []
    par = 0
    # Percorre a lista juntando os elementos nas possibilidades possíveis
    for element in aux:
        lmt = max(element) + 1
        if par == 0:
            for j in range(lmt + 1):
                pilha.append(element + [j])
        else:
            # Range invertido
            for j in range(lmt + 1)[::-1]:
                pilha.append(element + [j])
        par = par ^ 1
    return pilha

n = int(input())
# Gera as combinações de pilhas de brinquedos
possibilidades = combinacoes(n)
# Imprime a quantidade de combinações
print(len(possibilidades))
# Formata a Impressão como é pedido no problema
for item in possibilidades:
    arranjos = ''
    limit = max(item) + 1
    # Percorre os limites para descobrir em qual grupo o brinquedo pertence
    for group in range(limit):
        arranjos += '{'
        toys = ''
        for i in range(n):
            if item[i] == group:
                toys += '{0},'.format(i + 1)
        arranjos += toys[:-1]
        arranjos += '},'
    print(arranjos[:-1])

```


496_A. Minimum Difficulty

Mike is trying rock climbing but he is awful at it.

There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.

Today Mike decided to cover the track with holds hanging on heights a1, ..., an. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1, 2, 3, 4, 5) and remove the third element from it, we obtain the sequence (1, 2, 4, 5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.

Help Mike determine the minimum difficulty of the track after removing one hold.

Input

The first line contains a single integer n (3 ≤ n ≤ 100) — the number of holds.

The next line contains n space-separated integers ai (1 ≤ ai ≤ 1000), where ai is the height where the hold number i hangs. The sequence ai is increasing (i.e. each element except for the first one is strictly larger than the previous one).

Output

Print a single number — the minimum difficulty of the track after removing a single hold.

Examples

Input

3
1 4 6

Output

5

Input

5
1 2 3 4 5

Output

2

Input

5
1 2 3 7 8

Output

4

Note

In the first sample you can remove only the second hold, then the sequence looks like (1, 6), the maximum difference of the neighboring elements equals 5.

In the second test after removing every hold the difficulty equals 2.

In the third test you can obtain sequences (1, 3, 7, 8), (1, 2, 7, 8), (1, 2, 3, 8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer — 4.

```python
n=int(input())
lis=list(map(int,input().split()))
dif=abs(lis[1]-lis[0])
pos=[]
for i in range(n-1):
    #print(i,end=",")
    if(abs(lis[i]-lis[i+1])>dif):
        dif=abs(lis[i]-lis[i+1])
for i in range(1,n-1):
    t=abs(lis[i-1]-lis[i+1])
    if(t>dif):
        pos.append(t)
    else:
        pos.append(dif)
#print(dif)
print(min(pos))

```


51_D. Geometrical problem

Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.

In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.

Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.

Input

The first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.

Output

Print 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.

Examples

Input

4
3 6 12 24

Output

0

Input

4
-8 -16 24 -32

Output

1

Input

4
0 1 2 3

Output

2

```python
def main():
    n = int(input())
    l = tuple(map(int, input().split()))
    if n == 1:
        return 0
    if n == 2:
        if l[0] == 0 and l[1] != 0: return 1
        return 0
    def div(a, b):
        if b == 0: return 0 if a == 0 else "inf"
        return a / b
    pref, suff = [["init", 1]], [["init", 1]]
    for i in range(1, n):
        d = div(l[i], l[i-1])
        if pref[-1][0] == "init":
            pass
        elif d != pref[-1][0]:
            for j in range(i, n):
                pref += [["null", 0]]
            break
        pref += [[d, 1]]
    for i in range(n - 1, -1, -1):
        d = div(l[i], l[i-1])
        if l[i - 1] == 0 and l[i] != 0:
            suff[-1][0] = suff[-2][0] if len(suff) > 1 else 1
        if d != suff[-1][0] and suff[-1][0] != "init":
            for j in range(i-1, -1,-1):
                suff += [["null", 0]]
            break
        suff += [[d, 1]]
    #print(pref)
    #print(suff)
    if pref[-1][1] == 1: return 0
    if pref[-2][1] == 1 or suff[-2][1] == 1: return 1

    for i in range(1,n-1):
        pr, sf = pref[i - 1], suff[n - i - 2]
        dv = div(l[i+1], l[i-1])
        #print(pr,sf,dv,l[i-1:i+2])
        if pr[0] == "init" and sf[0] == "init": return 1
        if pr[0] == "init" and dv == sf[0]:
            return 1
        elif sf[0] == "init" and dv == pr[0]:
            return 1
        elif dv == pr[0] and dv == sf[0]:
            return 1
    return 2
print(main())

```


546_E. Soldier and Traveling

In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.

Check if is it possible that after roaming there will be exactly bi soldiers in the i-th city.

Input

First line of input consists of two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 200).

Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 100).

Next line contains n integers b1, b2, ..., bn (0 ≤ bi ≤ 100).

Then m lines follow, each of them consists of two integers p and q (1 ≤ p, q ≤ n, p ≠ q) denoting that there is an undirected road between cities p and q.

It is guaranteed that there is at most one road between each pair of cities.

Output

If the conditions can not be met output single word "NO".

Otherwise output word "YES" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if i ≠ j) or how many soldiers should stay in city i (if i = j).

If there are several possible answers you may output any of them.

Examples

Input

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

Output

YES
1 0 0 0
2 0 0 0
0 5 1 0
0 0 2 1

Input

2 0
1 2
2 1

Output

NO

```python
from sys import stdin
from collections import deque

def bfs(g, el, source, dest, pre):
	q = deque()
	pre.clear()
	pre.extend([None] * len(g))
	q.append(source)
	while q:
		u = q.popleft()
		for e in g[u]:
			v, c, f = el[e][1], el[e][2], el[e][3]
			if pre[v] is None and f < c and v != source:
				pre[v] = e
				q.append(v)
		if pre[dest] is not None:
			return True
	return False

def max_flow(g, el, source, sink):
	total_flow = 0
	pre = []
	while bfs(g, el, source, sink, pre):
		e = pre[sink]
		flow = int(1e9)
		path = []
		while True:
			flow = min(flow, el[e][2] - el[e][3])
			path.append(e)
			e = pre[el[e][0]]
			if e is None:
				break
		for e in path:
			el[e][3] += flow
			el[el[e][4]][3] -= flow
		total_flow += flow
	return total_flow

def add_edge(g, el, u, v, c):
	el.append([u, v, c, 0, len(el) + 1])
	el.append([v, u, 0, 0, len(el) - 1])
	g[u].append(len(el) - 2)
	g[v].append(len(el) - 1)

def main():
	n, m = [int(_) for _ in stdin.readline().split()]
	a = [int(_) for _ in stdin.readline().split()]
	b = [int(_) for _ in stdin.readline().split()]
	g = [[] for _ in range(n * 2 + 2)]
	el = []
	source = n * 2
	sink = n * 2 + 1
	inf = int(1e9)

	for line in stdin.readlines():
		u, v = [int(_) - 1 for _ in line.split()]
		add_edge(g, el, u, v + n, inf)
		add_edge(g, el, v, u + n, inf)

	for i in range(n):
		add_edge(g, el, i, i + n, a[i])
		add_edge(g, el, source, i, a[i])
		add_edge(g, el, i + n, sink, b[i])

	if sum(a) != sum(b) or max_flow(g, el, source, sink) != sum(a):
		print("NO")
	else:
		print("YES")
		tr = [[0 for j in range(n)] for i in range(n)]
		edges = [e for e in el if e[3] > 0 and e[0] < n * 2 and e[1] < n * 2]
		for edge in edges:
			def rev_idx(u):
				return u if u < n else u - n
			tr[rev_idx(edge[0])][rev_idx(edge[1])] = edge[3]
		print('\n'.join(' '.join(str(x) for x in row) for row in tr))

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


573_B. Bear and Blocks

Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.

Limak will repeat the following operation till everything is destroyed.

Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.

Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.

Input

The first line contains single integer n (1 ≤ n ≤ 105).

The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers.

Output

Print the number of operations needed to destroy all towers.

Examples

Input

6
2 1 4 6 2 2

Output

3

Input

7
3 3 3 1 3 3 3

Output

2

Note

The picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.

<image> After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.

```python
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase

def main():
    n=int(input())
    arr=list(map(int,input().split()))
    if n<3:
        print(1)
        exit()
    dp=[0]*(n)
    dp[0]=1
    dp[-1]=1
    # first find min time via left then min time via right .
    for i in range(1,n-1):
        if arr[i]<=arr[i-1]:
            dp[i]=min(arr[i],dp[i-1]+1)
        else:
            dp[i]=dp[i-1]+1
    ans=0
    for i in range(n-2,0,-1):
        if arr[i]>arr[i+1]:
            dp[i]=min(dp[i],dp[i+1]+1)
        else:
            dp[i]=min(dp[i],min(arr[i],1+dp[i+1]))
        ans=max(ans,dp[i])
    print(ans)

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

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

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

# endregion

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


616_C. The Labyrinth

You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.

Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.

For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently.

The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.

To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.

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

Input

The first line contains two integers n, m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the field.

Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells.

Output

Print the answer as a matrix as described above. See the examples to precise the format of the output.

Examples

Input

3 3
*.*
.*.
*.*

Output

3.3
.5.
3.3

Input

4 5
**..*
..***
.*.*.
*.*.*

Output

46..3
..732
.6.4.
5.4.3

Note

In first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner).

```python
from collections import deque

dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]

componentsizes = {}
componentid = 0

n, m = map(int, input().split())
field = [list(input()) for _ in range(n)]

def valid(y, x):
    return y >= 0 and x >= 0 and y < n and x < m

def component(y, x):
    size = 1
    q = deque([(y, x)])
    field[y][x] = componentid
    while q:
        y, x = q.pop()
        for i, j in dirs:
            if valid(y+i, x+j) and field[y+i][x+j] == ".":
                q.appendleft((y+i, x+j))
                field[y+i][x+j] = componentid
                size += 1
    return size

def solve(y, x):
    connected = set()
    for i, j in dirs:
        if valid(y+i, x+j) and type(field[y+i][x+j]) is int:
            connected.add(field[y+i][x+j])
    return (sum(componentsizes[i] for i in connected)+1)%10

for i in range(n):
    for j in range(m):
        if field[i][j] == ".":
            componentsizes[componentid] = component(i, j)
            componentid += 1

output = [[] for _ in range(n)]
for i in range(n):
    for j in range(m):
        output[i].append(str(solve(i, j)) if field[i][j] == "*" else ".")

print("\n".join(["".join(row) for row in output]))

```


635_D. Factory Repairs

A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.

Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.

As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.

Input

The first line contains five integers n, k, a, b, and q (1 ≤ k ≤ n ≤ 200 000, 1 ≤ b < a ≤ 10 000, 1 ≤ q ≤ 200 000) — the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.

The next q lines contain the descriptions of the queries. Each query is of one of the following two forms:

  * 1 di ai (1 ≤ di ≤ n, 1 ≤ ai ≤ 10 000), representing an update of ai orders on day di, or
  * 2 pi (1 ≤ pi ≤ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi?

It's guaranteed that the input will contain at least one query of the second type.

Output

For each query of the second type, print a line containing a single integer — the maximum number of orders that the factory can fill over all n days.

Examples

Input

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

Output

3
6
4

Input

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

Output

7
1

Note

Consider the first sample.

We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.

For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.

For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.

```python
from functools import reduce
class SegmentTree():
    def __init__(self, L, function = lambda x,y: x+y, initilizer = None):
        self.function = function
        self.initilizer = initilizer
        N = self.size = len(L)
        M = 1 << N.bit_length()
        self.margin = 2*M - N
        self.L = [None for i in range(self.margin)] + L
        for i in range(M-1, 0, -1):
            x, y = self.L[i<<1], self.L[i<<1|1]
            self.L[i] = None if x is None or y is None else function(x, y)
    def modify(self, pos, value):
        p = pos + self.margin
        self.L[p] = value
        while p > 1:
            x, y = self.L[p], self.L[p^1]
            if p&1: x, y = y, x
            self.L[p>>1] = None if x is None or y is None else self.function(x, y)
            p>>=1
    def query(self, left, right):
        l, r = left + self.margin, right + self.margin
        stack = []
        void = True
        if self.initilizer is not None:
            void = False
            result = self.initilizer
        while l < r:
            if l&1:
                if void:
                    result = self.L[l]
                    void = False
                else:
                    result = self.function(result, self.L[l])
                l+=1
            if r&1:
                r-=1
                stack.append(self.L[r])
            l>>=1
            r>>=1
        init = stack.pop() if void else result
        return reduce(self.function, reversed(stack), init)

import sys
n, k, a, b, q = [int(x) for x in input().split()]
orders = [0]*(n+2)
a_tree, b_tree = SegmentTree(orders, initilizer = 0), SegmentTree(orders, initilizer = 0)
for line in sys.stdin:
    s = [int(x) for x in line.split()]
    if s[0] == 1:
        orders[s[1]] += s[2]
        a_tree.modify(s[1], min(a, orders[s[1]]))
        b_tree.modify(s[1], min(b, orders[s[1]]))
    else:
        query = b_tree.query(0, s[1]) + a_tree.query(s[1]+k, n+1)
        print(query)

```


664_C. International Olympiad

International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.

For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.

You are given a list of abbreviations. For each of them determine the year it stands for.

Input

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.

Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

Output

For each abbreviation given in the input, find the year of the corresponding Olympiad.

Examples

Input

5
IAO'15
IAO'2015
IAO'1
IAO'9
IAO'0

Output

2015
12015
1991
1989
1990

Input

4
IAO'9
IAO'99
IAO'999
IAO'9999

Output

1989
1999
2999
9999

```python
from __future__ import print_function

dic = {"9":"1989","0":"1990","1":"1991","2":"1992","3":"1993","4":"1994","5":"1995","6":"1996","7":"1997","8":"1998"}

def get_year(s):
	# print("came into get_year")
	length=len(s)
	if len(s)==1:
		return dic[s]
	pos=[s]
	pre=1
	if s[0]=="0" or len(s)<4 or (len(s)==4 and int(s)<1989):
		pos=[]
		# pre=1
	# elif len(s)>4 or (len(s)==4 and int(s)>=1989):
	# 	pos=[s]
	# 	pre=1
	count=0
	while(count<length):
		# print(count)
		if int(str(pre)+s)>=1989:
			pos.append(str(pre)+s)
			count+=1
		pre+=1
	# print(s,pos)
	for i in range(1,length):
		# print(i)
		year = get_year(s[i:])
		try:
			pos.remove(year)
		except ValueError:
			pass
		# print(pos)
	# print(s,pos[0])
	# print(s,pos)
	return pos[0]

# occupied=[]
# for abb in abbs:
# 	length = len(abb)
# 	val = int(abb)
# 	if(val<10**(length-1))

# print(get_year("0003566"))
# print(get_year("9999"))
# print(get_year("999"))
# print(get_year("99"))
# print(get_year("9"))
m = int(input())

for i in range(m):
	x = input()
	abb = x[4:]
	print(int(get_year(abb)))

```


689_A. Mike and Cellphone

While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:

<image>

Together with his old phone, he lost all his contacts and now he can only remember the way his fingers moved when he put some number in. One can formally consider finger movements as a sequence of vectors connecting centers of keys pressed consecutively to put in a number. For example, the finger movements for number "586" are the same as finger movements for number "253":

<image> <image>

Mike has already put in a number by his "finger memory" and started calling it, so he is now worrying, can he be sure that he is calling the correct number? In other words, is there any other number, that has the same finger movements?

Input

The first line of the input contains the only integer n (1 ≤ n ≤ 9) — the number of digits in the phone number that Mike put in.

The second line contains the string consisting of n digits (characters from '0' to '9') representing the number that Mike put in.

Output

If there is no other phone number with the same finger movements and Mike can be sure he is calling the correct number, print "YES" (without quotes) in the only line.

Otherwise print "NO" (without quotes) in the first line.

Examples

Input

3
586

Output

NO

Input

2
09

Output

NO

Input

9
123456789

Output

YES

Input

3
911

Output

YES

Note

You can find the picture clarifying the first sample case in the statement above.

```python
n = int(input())
s = input()
fill = [[False for i in range(3)] for j in range(4)]
for i in s:
    if i == "0":
        j = 10
    else:
        j = ord(i)-ord('1') #0, 1, 2, 3... 8
    fill[j//3][j%3] = True
#for i in fill:
#    print(i)
top = fill[0][0] or fill[0][1] or fill[0][2]
bottom = fill[2][0] or fill[3][1] or fill[2][2]
left = fill[0][0] or fill[1][0] or fill[2][0]
right = fill[0][2] or fill[1][2] or fill[2][2]
#print(left, right, fill[3][1], (not left or not right)and not fill[3][1])
if ((not left or not right)and not fill[3][1]) or not top or not bottom:
    print("NO")
else:
    print("YES")

```


710_E. Generate a String

zscoder wants to generate an input file for some programming competition problem.

His input is a string consisting of n letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.

Initially, the text editor is empty. It takes him x seconds to insert or delete a letter 'a' from the text file and y seconds to copy the contents of the entire text file, and duplicate it.

zscoder wants to find the minimum amount of time needed for him to create the input file of exactly n letters 'a'. Help him to determine the amount of time needed to generate the input.

Input

The only line contains three integers n, x and y (1 ≤ n ≤ 107, 1 ≤ x, y ≤ 109) — the number of letters 'a' in the input file and the parameters from the problem statement.

Output

Print the only integer t — the minimum amount of time needed to generate the input file.

Examples

Input

8 1 1

Output

4

Input

8 1 10

Output

8


731_E. Funny Game

Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.

The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.

One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move.

Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.

Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally.

Input

The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall.

The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right.

Output

Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.

Examples

Input

3
2 4 8

Output

14

Input

4
1 -7 -2 3

Output

-3

Note

In the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.

In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value  - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be  - 3.


777_A. Shell Game

Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball.

Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.).

Let's number shells from 0 to 2 from left to right. Thus the left shell is assigned number 0, the middle shell is 1 and the right shell is 2. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly n movements were made by the operator and the ball was under shell x at the end. Now he wonders, what was the initial position of the ball?

Input

The first line of the input contains an integer n (1 ≤ n ≤ 2·109) — the number of movements made by the operator.

The second line contains a single integer x (0 ≤ x ≤ 2) — the index of the shell where the ball was found after n movements.

Output

Print one integer from 0 to 2 — the index of the shell where the ball was initially placed.

Examples

Input

4
2

Output

1

Input

1
1

Output

0

Note

In the first sample, the ball was initially placed beneath the middle shell and the operator completed four movements.

  1. During the first move operator swapped the left shell and the middle shell. The ball is now under the left shell.
  2. During the second move operator swapped the middle shell and the right one. The ball is still under the left shell.
  3. During the third move operator swapped the left shell and the middle shell again. The ball is again in the middle.
  4. Finally, the operators swapped the middle shell and the right shell. The ball is now beneath the right shell.

```python
def nap(y):
    if y==0:
        p=[0,1,2]
        return p
    if y==1:
        p=[1,0,2]
        return p
    if y==2:
        p=[1,2,0]
        return p
    if y==3:
        p=[2,1,0]
        return p
    if y==4:
        p=[2,0,1]
        return p
    if y==5:
        p=[0,2,1]
        return p
n=int(input())
x=int(input())
n=n%6
m=nap(n)
print(m[x])

```


801_D. Volatile Kite

You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.

You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.

Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.

Input

The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices.

The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).

Output

Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex.

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

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

Examples

Input

4
0 0
0 1
1 1
1 0

Output

0.3535533906

Input

6
5 0
10 0
12 -4
10 -8
5 -8
3 -4

Output

1.0000000000

Note

Here is a picture of the first sample

<image>

Here is an example of making the polygon non-convex.

<image>

This is not an optimal solution, since the maximum distance we moved one point is  ≈ 0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most  ≈ 0.3535533906.


822_A. I'm bored with life

Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!

Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1·2·3·...·(x - 1)·x. For example 4! = 1·2·3·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.

Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?

Input

The first and single line contains two integers A and B (1 ≤ A, B ≤ 109, min(A, B) ≤ 12).

Output

Print a single integer denoting the greatest common divisor of integers A! and B!.

Example

Input

4 3

Output

6

Note

Consider the sample.

4! = 1·2·3·4 = 24. 3! = 1·2·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6.

```python

arr1 = input().split()
a = int(arr1[0])
b = int(arr1[1])
c = int(min(a, b))

res = 1
for i in range(2, c+1):
    res *= i
print(res)
```


847_F. Berland Elections

The elections to Berland parliament are happening today. Voting is in full swing!

Totally there are n candidates, they are numbered from 1 to n. Based on election results k (1 ≤ k ≤ n) top candidates will take seats in the parliament.

After the end of the voting the number of votes for each candidate is calculated. In the resulting table the candidates are ordered by the number of votes. In case of tie (equal number of votes) they are ordered by the time of the last vote given. The candidate with ealier last vote stands higher in the resulting table.

So in the resulting table candidates are sorted by the number of votes (more votes stand for the higher place) and if two candidates have equal number of votes they are sorted by the time of last vote (earlier last vote stands for the higher place).

There is no way for a candidate with zero votes to take a seat in the parliament. So it is possible that less than k candidates will take a seat in the parliament.

In Berland there are m citizens who can vote. Each of them will vote for some candidate. Each citizen will give a vote to exactly one of n candidates. There is no option "against everyone" on the elections. It is not accepted to spoil bulletins or not to go to elections. So each of m citizens will vote for exactly one of n candidates.

At the moment a citizens have voted already (1 ≤ a ≤ m). This is an open election, so for each citizen it is known the candidate for which the citizen has voted. Formally, the j-th citizen voted for the candidate gj. The citizens who already voted are numbered in chronological order; i.e. the (j + 1)-th citizen voted after the j-th.

The remaining m - a citizens will vote before the end of elections, each of them will vote for one of n candidates.

Your task is to determine for each of n candidates one of the three possible outcomes:

  * a candidate will be elected to the parliament regardless of votes of the remaining m - a citizens;
  * a candidate has chance to be elected to the parliament after all n citizens have voted;
  * a candidate has no chances to be elected to the parliament regardless of votes of the remaining m - a citizens.

Input

The first line contains four integers n, k, m and a (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100, 1 ≤ a ≤ m) — the number of candidates, the number of seats in the parliament, the number of Berland citizens and the number of citizens who already have voted.

The second line contains a sequence of a integers g1, g2, ..., ga (1 ≤ gj ≤ n), where gj is the candidate for which the j-th citizen has voted. Citizens who already voted are numbered in increasing order of voting times.

Output

Print the sequence consisting of n integers r1, r2, ..., rn where:

  * ri = 1 means that the i-th candidate is guaranteed to take seat in the parliament regardless of votes of the remaining m - a citizens;
  * ri = 2 means that the i-th candidate has a chance to take a seat in the parliament, i.e. the remaining m - a citizens can vote in such a way that the candidate will take a seat in the parliament;
  * ri = 3 means that the i-th candidate will not take a seat in the parliament regardless of votes of the remaining m - a citizens.

Examples

Input

3 1 5 4
1 2 1 3

Output

1 3 3

Input

3 1 5 3
1 3 1

Output

2 3 2

Input

3 2 5 3
1 3 1

Output

1 2 2

```python
class State:
  __slots__ = ['candidate', 'votes', 'last_vote']

  def __init__(self, cand, votes, last):
    self.candidate = cand
    self.votes = votes
    self.last_vote = last

  def beats(self, other, extra):
    return self.votes + extra > other.votes

def main():
  candidates, seats, people, voted = map(int, input().split())
  votes = [0 for i in range(candidates)]
  last_vote = [0 for i in range(candidates)]

  if candidates == 1:
    print(1)
    return

  v = list(map(int, input().split()))
  for t in range(voted):
    cand = v[t] - 1
    votes[cand] += 1
    last_vote[cand] = t

  states = [State(i, votes[i], last_vote[i]) for i in range(candidates)]
  states = sorted(states, key = lambda x : (x.votes, -x.last_vote))
  res = [0 for i in range(candidates)]

  for i in range(candidates):
    if i < candidates - seats:
      low = candidates - seats
      if states[i].beats(states[low], people - voted):
        res[states[i].candidate] = 2
      else:
        res[states[i].candidate] = 3
    else:
      extra = people - voted
      other = i - 1
      place = i

      if extra == 0 and states[i].votes == 0:
        res[states[i].candidate] = 3
        continue

      while other >= 0 and extra > 0:
        needed = states[i].votes - states[other].votes + 1
        if needed <= extra:
          extra -= needed;
          place -= 1
          other -= 1
        else:
          break

      res[states[i].candidate] = (1 if place + seats >= candidates and states[i].votes > 0 else 2)

  for i in res:
    print(i, end = ' ')

main()

```


869_A. The Artful Expedient

Rock... Paper!

After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.

A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted by x1, x2, ..., xn and y1, y2, ..., yn respectively. They reveal their sequences, and repeat until all of 2n integers become distinct, which is the only final state to be kept and considered.

Then they count the number of ordered pairs (i, j) (1 ≤ i, j ≤ n) such that the value xi xor yj equals to one of the 2n integers. Here xor means the [bitwise exclusive or](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) operation on two integers, and is denoted by operators ^ and/or xor in most programming languages.

Karen claims a win if the number of such pairs is even, and Koyomi does otherwise. And you're here to help determine the winner of their latest game.

Input

The first line of input contains a positive integer n (1 ≤ n ≤ 2 000) — the length of both sequences.

The second line contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 2·106) — the integers finally chosen by Koyomi.

The third line contains n space-separated integers y1, y2, ..., yn (1 ≤ yi ≤ 2·106) — the integers finally chosen by Karen.

Input guarantees that the given 2n integers are pairwise distinct, that is, no pair (i, j) (1 ≤ i, j ≤ n) exists such that one of the following holds: xi = yj; i ≠ j and xi = xj; i ≠ j and yi = yj.

Output

Output one line — the name of the winner, that is, "Koyomi" or "Karen" (without quotes). Please be aware of the capitalization.

Examples

Input

3
1 2 3
4 5 6

Output

Karen

Input

5
2 4 6 8 10
9 7 5 3 1

Output

Karen

Note

In the first example, there are 6 pairs satisfying the constraint: (1, 1), (1, 2), (2, 1), (2, 3), (3, 2) and (3, 3). Thus, Karen wins since 6 is an even number.

In the second example, there are 16 such pairs, and Karen wins again.

```python
# Main maut ko takiya, aur kafan ko chaadar banakar audhta hoon!

print("Karen")
```


916_A. Jamie and Alarm Snooze

Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to know what is the smallest number of times he needs to press the snooze button.

A time is considered lucky if it contains a digit '7'. For example, 13: 07 and 17: 27 are lucky, while 00: 48 and 21: 34 are not lucky.

Note that it is not necessary that the time set for the alarm and the wake-up time are on the same day. It is guaranteed that there is a lucky time Jamie can set so that he can wake at hh: mm.

Formally, find the smallest possible non-negative integer y such that the time representation of the time x·y minutes before hh: mm contains the digit '7'.

Jamie uses 24-hours clock, so after 23: 59 comes 00: 00.

Input

The first line contains a single integer x (1 ≤ x ≤ 60).

The second line contains two two-digit integers, hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).

Output

Print the minimum number of times he needs to press the button.

Examples

Input

3
11 23

Output

2

Input

5
01 07

Output

0

Note

In the first sample, Jamie needs to wake up at 11:23. So, he can set his alarm at 11:17. He would press the snooze button when the alarm rings at 11:17 and at 11:20.

In the second sample, Jamie can set his alarm at exactly at 01:07 which is lucky.

```python
def lucky(a,b):
    return '7' in str(a)+str(b)
x = int(input())
t = 0
h,m = map(int,input().split())
while not lucky(h,m):
    t+=1
    m -= x
    while m<0:
        m+=60
        h-=1
    h%=24
print(t)

```


939_B. Hamster Farm

Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.

Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.

Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.

Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.

Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.

Input

The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces.

The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.

Output

Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input.

If there are many correct answers, output any of them.

Examples

Input

19 3
5 4 10

Output

2 4

Input

28 3
5 6 30

Output

1 5

```python
# -*- coding: utf-8 -*-
"""
Created on Fri Mar  2 22:09:34 2018

@author: Xiaohua
"""

def Hamster(amounts,boxsize):

    a=10000000000000000000
    result=[0,0]
    for i in range(0,len(boxsize)):
        if(amounts[0]%boxsize[i]<a):
            a=amounts[0]%boxsize[i]
            result[0]=i+1
            result[1]=int(amounts[0]//boxsize[i])

    return  (str(result[0])+" "+str(result[1])  )

def hello():
    """Print "Hello World" and return None"""
    amounts = list(map(int, input().strip().split(' ')))
    boxsize = list(map(int, input().strip().split(' ')))

    result=Hamster(amounts,boxsize)
    print(result)
# main program starts here
hello()
```


991_E. Bus Number

This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.

In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number n.

In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too.

Given n, determine the total number of possible bus number variants.

Input

The first line contains one integer n (1 ≤ n ≤ 10^{18}) — the number of the bus that was seen by Vasya. It is guaranteed that this number does not start with 0.

Output

Output a single integer — the amount of possible variants of the real bus number.

Examples

Input

97

Output

2

Input

2028

Output

13

Note

In the first sample, only variants 97 and 79 are possible.

In the second sample, the variants (in the increasing order) are the following: 208, 280, 802, 820, 2028, 2082, 2208, 2280, 2802, 2820, 8022, 8202, 8220.

```python
from itertools import chain, combinations
from collections import defaultdict
import math

def powerset(iterable):
    xs = iterable
    return chain.from_iterable(combinations(xs,n) for n in range(1, len(xs)+1))

def has(s):
	h = 1
	p = [2,3,5,7,11,13,17,19,23,29]
	for i in s:
		h *= p[i-1]
	return h

h = set()
total = 0
inp = input().strip()
if int(inp) == 1000000000000000000:
	print(18)
else:
	ok = [int(i) for i in inp]
	require = set(ok)

	for s in powerset(ok):
		if has(s) in h:
			continue

		h.add(has(s))

		d = defaultdict(int)
		prod = 1
		for c in s:
			d[c] += 1
			prod *= d[c]

		flag = False
		for i in require:
			if d[i] == 0:
				flag = True
				break
		if flag: continue

		n = len(s)
		total += (n-d[0])*math.factorial(n-1)/prod

	print(int(total))
```


p02620 Introduction to Heuristics Contest - Incremental Scoring

You will be given a contest schedule for D days and M queries of schedule modification. In the i-th query, given integers d_i and q_i, change the type of contest to be held on day d_i to q_i, and then output the final satisfaction at the end of day D on the updated schedule. Note that we do not revert each query. That is, the i-th query is applied to the new schedule obtained by the (i-1)-th query.

Input

Input is given from Standard Input in the form of the input of Problem A followed by the output of Problem A and the queries.

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}
t_1
t_2
\vdots
t_D
M
d_1 q_1
d_2 q_2
\vdots
d_M q_M

* The constraints and generation methods for the input part are the same as those for Problem A.
* For each d=1,\ldots,D, t_d is an integer generated independently and uniformly at random from {1,2,\ldots,26}.
* The number of queries M is an integer satisfying 1\leq M\leq 10^5.
* For each i=1,\ldots,M, d_i is an integer generated independently and uniformly at random from {1,2,\ldots,D}.
* For each i=1,\ldots,26, q_i is an integer satisfying 1\leq q_i\leq 26 generated uniformly at random from the 25 values that differ from the type of contest on day d_i.

Output

Let v_i be the final satisfaction at the end of day D on the schedule after applying the i-th query. Print M integers v_i to Standard Output in the following format:

v_1
v_2
\vdots
v_M

Output

Let v_i be the final satisfaction at the end of day D on the schedule after applying the i-th query. Print M integers v_i to Standard Output in the following format:

v_1
v_2
\vdots
v_M

Example

Input

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192
1
17
13
14
13
5
1 7
4 11
3 4
5 24
4 19

Output

72882
56634
38425
27930
42884

```python
NTEST = 26

D=int(input())

C=list(map(int,input().split()))

SL=list()
SL.append([0 for i in range(NTEST)])
for d in range(D):
    S=list(map(int,input().split()))
    SL.append(S)

tests=list()
tests.append(0)
for d in range(D):
    tests.append(int(input()))

def calcSat(test_applied):
    lastDay = [0 for i in range(NTEST)]

    sat = 0
    for d in range(1,D+1):
        tst = test_applied[d] - 1
        lastDay[tst] = d
        sat += SL[d][tst]
        for itst in range(NTEST):
            sat -= C[itst] * (d-lastDay[itst])
    return sat

satList = list()
satList.append(0)
lastDay = [[0 for i in range(NTEST)]]

def calcSat_with_memo(test_applied):

    total_sat = 0
    for d in range(1,D+1):
        lastDay.append(list(lastDay[d-1]))
        sat = 0
        tst = test_applied[d] - 1
        lastDay[d][tst] = d
        sat += SL[d][tst]
        for itst in range(NTEST):
            sat -= C[itst] * (d-lastDay[d][itst])
        satList.append(sat)
        total_sat += sat

    return total_sat

def recalcSat_with_memo(total_sat_before, tday, t_from, t_to, test_applied):

    d_total_sat = 0

    lastDay[tday][t_from -1]=lastDay[tday-1][t_from -1]
    d_sat=0
    d_sat += (SL[tday][t_to -1]-SL[tday][t_from -1])
    d_sat += C[t_to -1]*(tday - lastDay[tday][t_to -1])
    d_sat -= C[t_from -1]*(tday - lastDay[tday][t_from -1])

    lastDay[tday][t_to -1]=tday

    satList[tday]+= d_sat
    d_total_sat  += d_sat

    old_last = tday
    new_last = lastDay[tday][t_from -1]
    for d in range(tday+1,D+1):
        if test_applied[d] == t_from :
            break
        d_sat = C[t_from -1]*(- old_last + new_last)
        lastDay[d][t_from -1] = new_last
        satList[d]+= d_sat
        d_total_sat += d_sat

    old_last = lastDay[tday-1][t_to -1]
    new_last = tday
    for d in range(tday+1,D+1):
        if test_applied[d] == t_to :
            break
        d_sat = C[t_to -1]*(- old_last + new_last)
        lastDay[d][t_to -1] = new_last
        satList[d]+= d_sat
        d_total_sat += d_sat

    return d_total_sat

# sat = calcSat(tests)
# print(sat)

sat = calcSat_with_memo(tests)
# print(sat)

# -------------------
M=int(input())

ans = list()

for m in range(M):
    d, new_tst = list(map(int, input().split()))

    d_sat = recalcSat_with_memo(sat, d, tests[d], new_tst, tests)

    tests[d] = new_tst
    sat += d_sat
    ans.append(sat)

for m in range(M):
    print(ans[m])

```


p02751 Social Infrastructure Information Systems Division  Hitachi Programming Contest 2020 - Odd Sum Rectangles

We have a grid with (2^N - 1) rows and (2^M-1) columns. You are asked to write 0 or 1 in each of these squares. Let a_{i,j} be the number written in the square at the i-th row from the top and the j-th column from the left.

For a quadruple of integers (i_1, i_2, j_1, j_2) such that 1\leq i_1 \leq i_2\leq 2^N-1, 1\leq j_1 \leq j_2\leq 2^M-1, let S(i_1, i_2, j_1, j_2) = \displaystyle \sum_{r=i_1}^{i_2}\sum_{c=j_1}^{j_2}a_{r,c}. Then, let the oddness of the grid be the number of quadruples (i_1, i_2, j_1, j_2) such that S(i_1, i_2, j_1, j_2) is odd.

Find a way to fill in the grid that maximizes its oddness.

Constraints

* N and M are integers between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N M

Output

Print numbers to write in the grid so that its oddness is maximized, in the following format:

a_{1,1}a_{1,2}\cdots a_{1,2^M-1}
a_{2,1}a_{2,2}\cdots a_{2,2^M-1}
\vdots
a_{2^N-1,1}a_{2^N-1,2}\cdots a_{2^N-1,2^M-1}

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

Example

Input

1 2

Output

111

```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def hadamard(n):
        if mem[n] != None:
            return mem[n]
        h = hadamard(n-1)
        res = [[j for j in i] for i in h]
        res_ = [[j for j in i] for i in h]
        for i in range(len(res)):
            res[i] += [j for j in h[i]]
            res_[i] += [j^1 for j in h[i]]
        res += res_
        mem[n] = res
        return res

    n,m = LI()
    f = 0
    if m < n:
        n,m = m,n
        f = 1
    h,w = 1<<n, 1<<m
    mem = defaultdict(lambda : None)
    mem[0] = [[0]]
    s = hadamard(m)[:h]
    if f:
        s = [[s[j][i] for j in range(h)] for i in range(w)]
        h,w = w,h
    for x in range(w):
        for y in range(h-1)[::-1]:
            s[y+1][x] ^= s[y][x]
    for y in range(h):
        for x in range(w-1)[::-1]:
            s[y][x+1] ^= s[y][x]
    ans = [i[1:] for i in s[1:]]
    for i in ans:
        print(*i,sep="")
    return

#Solve
if __name__ == "__main__":
    solve()

```


p02886 AtCoder Beginner Contest 143 - TAKOYAKI FESTIVAL 2019

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

* All values in input are integers.
* 2 \leq N \leq 50
* 0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Examples

Input

3
3 1 2

Output

11

Input

7
5 0 7 8 3 3 2

Output

312

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

print(sum(l[i]*sum(l[i+1:]) for i in range(len(l)-1)))

```