p02781 AtCoder Beginner Contest 154 - Almost Everywhere Zero

Find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.

Constraints

* 1 \leq N < 10^{100}
* 1 \leq K \leq 3

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the count.

Examples

Input

100
1

Output

19

Input

25
2

Output

14

Input

314159
2

Output

937

Input

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
3

Output

117879300

```python
import functools
import sys

@functools.lru_cache(None)
def doit(n, k):
    if len(n) == 0 or k < 0:
        return k == 0
    d = int(n[0])
    return sum(doit(n[1:] if i == d else '9' * (len(n) - 1), k - 1 if i > 0 else k) for i in range(d + 1))

sys.setrecursionlimit(404)
print(doit(input(), int(input())))

```


p02916 AtCoder Beginner Contest 140 - Buffet

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

* All values in input are integers.
* 2 \leq N \leq 20
* 1 \leq A_i \leq N
* A_1, A_2, ..., A_N are all different.
* 1 \leq B_i \leq 50
* 1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Examples

Input

3
3 1 2
2 5 4
3 6

Output

14

Input

4
2 3 4 1
13 5 8 24
45 9 15

Output

74

Input

2
1 2
50 50
50

Output

150

```python
N=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
C=list(map(int,input().split()))
pnt=sum(B)
for i in range(N-1):
  if A[i+1]==A[i]+1:
    pnt+=C[A[i]-1]

print(pnt)
```


p03194 CADDi 2018 for Beginners - Product and GCD

There are N integers a_1, a_2, ..., a_N not less than 1. The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

* 1 \leq N \leq 10^{12}
* 1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Examples

Input

3 24

Output

2

Input

5 1

Output

1

Input

1 111

Output

111

Input

4 972439611840

Output

206

```python
import math
import collections
# 試し割法

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

def trial_division(n):
    # 素因数を格納するリスト
    factor = []
    # 2から√n以下の数字で割っていく
    tmp = int(math.sqrt(n)) + 1
    for num in range(2, tmp):
        while n % num == 0:
            n //= num
            factor.append(num)
    # リストが空ならそれは素数
    if not factor:
        return [n]
    else:
        factor.append(n)
        return factor

lst = trial_division(P)
c_lst = collections.Counter(lst)

ans = 1
for k, v in c_lst.items():
    while v >= N:
        ans *= k
        v -= N
print(ans)

```


p03343 AtCoder Regular Contest 098 - Range Minimum Queries

You are given an integer sequence A of length N and an integer K. You will perform the following operation on this sequence Q times:

* Choose a contiguous subsequence of length K, then remove the smallest element among the K elements contained in the chosen subsequence (if there are multiple such elements, choose one of them as you like).

Let X and Y be the values of the largest and smallest element removed in the Q operations. You would like X-Y to be as small as possible. Find the smallest possible value of X-Y when the Q operations are performed optimally.

Constraints

* 1 \leq N \leq 2000
* 1 \leq K \leq N
* 1 \leq Q \leq N-K+1
* 1 \leq A_i \leq 10^9
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K Q
A_1 A_2 ... A_N

Output

Print the smallest possible value of X-Y.

Examples

Input

5 3 2
4 3 1 5 2

Output

1

Input

10 1 6
1 1 2 3 5 8 13 21 34 55

Output

7

Input

11 7 5
24979445 861648772 623690081 433933447 476190629 262703497 211047202 971407775 628894325 731963982 822804784

Output

451211184

```python
N, K, Q = map(int, input().split())
X = list(map(int, input().split()))

r = 10**18
for y in X:
    tmp = []
    tmp2 = []
    for x in X:
        if x < y:
            tmp.sort()
            tn = len(tmp)
            if len(tmp) > K-1:
                tmp2 += tmp[:tn-K+1]
            tmp = []
            continue
        tmp.append(x)
    tmp.sort()
    tn = len(tmp)
    if tn-K+1 > 0:
        tmp2 += tmp[:tn-K+1]
    tmp2.sort()
    if len(tmp2) >= Q:
        r = min(r, tmp2[Q-1] - y)
print(r)

```


p03503 AtCoder Beginner Contest 080 - Shopping Street

Joisino is planning to open a shop in a shopping street.

Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those periods.

There are already N stores in the street, numbered 1 through N.

You are given information of the business hours of those shops, F_{i,j,k}. If F_{i,j,k}=1, Shop i is open during Period k on Day j (this notation is explained below); if F_{i,j,k}=0, Shop i is closed during that period. Here, the days of the week are denoted as follows. Monday: Day 1, Tuesday: Day 2, Wednesday: Day 3, Thursday: Day 4, Friday: Day 5. Also, the morning is denoted as Period 1, and the afternoon is denoted as Period 2.

Let c_i be the number of periods during which both Shop i and Joisino's shop are open. Then, the profit of Joisino's shop will be P_{1,c_1}+P_{2,c_2}+...+P_{N,c_N}.

Find the maximum possible profit of Joisino's shop when she decides whether her shop is open during each period, making sure that it is open during at least one period.

Constraints

* 1≤N≤100
* 0≤F_{i,j,k}≤1
* For every integer i such that 1≤i≤N, there exists at least one pair (j,k) such that F_{i,j,k}=1.
* -10^7≤P_{i,j}≤10^7
* All input values are integers.

Input

Input is given from Standard Input in the following format:

N
F_{1,1,1} F_{1,1,2} ... F_{1,5,1} F_{1,5,2}
:
F_{N,1,1} F_{N,1,2} ... F_{N,5,1} F_{N,5,2}
P_{1,0} ... P_{1,10}
:
P_{N,0} ... P_{N,10}

Output

Print the maximum possible profit of Joisino's shop.

Examples

Input

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

Output

8

Input

2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1

Output

-2

Input

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

Output

23

```python
n = int(input())
f = [[int(x) for x in input().split()] for i in range(n)]
p = [[int(x) for x in input().split()] for i in range(n)]
t={i:0 for i in range(1,2**10)}
for i in range(1,2**10):
  d, b={j:0 for j in range(n)}, format(i, "010b")
  for j in range(n):
    for k in range(10):
      if (i>>k)%2&f[j][k]==1: d[j]+=1
    t[i]+=p[j][d[j]]
print(max(t.values()))
```


p03664 AtCoder Regular Contest 078 - Mole and Abandoned Mine

Mole decided to live in an abandoned mine. The structure of the mine is represented by a simple connected undirected graph which consists of N vertices numbered 1 through N and M edges. The i-th edge connects Vertices a_i and b_i, and it costs c_i yen (the currency of Japan) to remove it.

Mole would like to remove some of the edges so that there is exactly one path from Vertex 1 to Vertex N that does not visit the same vertex more than once. Find the minimum budget needed to achieve this.

Constraints

* 2 \leq N \leq 15
* N-1 \leq M \leq N(N-1)/2
* 1 \leq a_i, b_i \leq N
* 1 \leq c_i \leq 10^{6}
* There are neither multiple edges nor self-loops in the given graph.
* The given graph is connected.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
:
a_M b_M c_M

Output

Print the answer.

Examples

Input

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

Output

200

Input

2 1
1 2 1

Output

0

Input

15 22
8 13 33418
14 15 55849
7 10 15207
4 6 64328
6 9 86902
15 7 46978
8 14 53526
1 2 8720
14 12 37748
8 3 61543
6 5 32425
4 11 20932
3 12 55123
8 2 45333
9 12 77796
3 9 71922
12 15 70793
2 4 25485
11 6 1436
2 7 81563
7 11 97843
3 1 40491

Output

133677

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

g = [[0 for j in range(n)] for i in range(n)]

for i in range(m):
    u, v, w = map(int, input().split())
    g[u - 1][v - 1] = g[v - 1][u - 1] = w

e = [sum(g[i][j] for i in range(n) if S >> i & 1 for j in range(i + 1, n) if S >> j & 1) for S in range(1 << n)]

dp = [[-10 ** 9 for j in range(n)] for i in range(1 <<  n)]

for i in range(1 << n):
    for j in range(n):
        if i >> j & 1:
            if not j:
                dp[i][j] = e[i]
            else:
                for k in range(n):
                    if  j != k and (i >> k & 1) and g[k][j]:
                        dp[i][j] = max(dp[i][j], dp[i ^ (1 << j)][k] + g[k][j])
                s = i ^ (1 << j)
                k = s
                while k:
                    dp[i][j] = max(dp[i][j], dp[i ^ k][j] + e[k | 1 << j])
                    k = (k - 1) & s

print(e[(1 << n) - 1] - dp[(1 << n) - 1][n - 1])
```


p03819 AtCoder Regular Contest 068 - Snuke Line

Snuke has decided to play a game, where the player runs a railway company. There are M+1 stations on Snuke Line, numbered 0 through M. A train on Snuke Line stops at station 0 and every d-th station thereafter, where d is a predetermined constant for each train. For example, if d = 3, the train stops at station 0, 3, 6, 9, and so forth.

There are N kinds of souvenirs sold in areas around Snuke Line. The i-th kind of souvenirs can be purchased when the train stops at one of the following stations: stations l_i, l_i+1, l_i+2, ..., r_i.

There are M values of d, the interval between two stops, for trains on Snuke Line: 1, 2, 3, ..., M. For each of these M values, find the number of the kinds of souvenirs that can be purchased if one takes a train with that value of d at station 0. Here, assume that it is not allowed to change trains.

Constraints

* 1 ≦ N ≦ 3 × 10^{5}
* 1 ≦ M ≦ 10^{5}
* 1 ≦ l_i ≦ r_i ≦ M

Input

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

N M
l_1 r_1
:
l_{N} r_{N}

Output

Print the answer in M lines. The i-th line should contain the maximum number of the kinds of souvenirs that can be purchased if one takes a train stopping every i-th station.

Examples

Input

3 3
1 2
2 3
3 3

Output

3
2
2

Input

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

Output

7
6
6
5
4
5
5
3
2

```python
class BIT:
    def __init__(self, n):
        self.n = n
        self.bit = [0] * (n + 1)

    def add(self, k, x):
        while k <= self.n:
            self.bit[k] += x
            k += k & -k

    def sum(self, k):
        s = 0
        while k > 0:
            s += self.bit[k]
            k -= k & -k
        return s

n, m = map(int, input().split())
st = BIT(m)
L, R = [], []
d = [[] for i in range(m + 1)]
for i in range(n):
    l, r = map(int, input().split())
    L.append(l)
    R.append(r)
    d[r - l + 1].append(i)

num = n
for i in range(1, m + 1):
    num -= len(d[i])
    for j in d[i]:
        st.add(L[j], 1)
        st.add(R[j] + 1, -1)

    tmp = 0
    k = i
    for j in range(k, m + 1, i):
        tmp += st.sum(j)

    print(num + tmp)

```


p03986 AtCoder Grand Contest 005 - STring

We have a string X, which has an even number of characters. Half the characters are `S`, and the other half are `T`.

Takahashi, who hates the string `ST`, will perform the following operation 10^{10000} times:

* Among the occurrences of `ST` in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

* 2 ≦ |X| ≦ 200,000
* The length of X is even.
* Half the characters in X are `S`, and the other half are `T`.

Input

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

X

Output

Print the eventual length of X.

Examples

Input

TSTTSS

Output

4

Input

SSTTST

Output

0

Input

TSSTTTSS

Output

4

```python
x=input()
s=0;t=0
for i in range(len(x)):
  if x[i]=='S':s+=1
  elif s==0:t+=1
  else:s-=1
print(s+t)
```


p00074 Videotape

There is a 120 minute videotape with standard recording. When I set the VCR counter to 00:00:00 with the tape completely rewound and recorded in standard recording mode, I got a certain counter value. Enter this counter value (hours, minutes, seconds), find the length of the remaining tape (recordable time), and create a program that outputs in the format of hours: minutes: seconds.

However, the input must be within 2 hours (120 minutes). The remaining amount of tape is calculated in two ways, standard recording mode and triple recording mode, and outputs two digits each for hours, minutes, and seconds as shown in the output example. If the tens digit is 0, such as "05", add "0".

input

Given multiple datasets. Each dataset is as follows.

T H S

T, H, and S are integers that represent hours, minutes, and seconds, respectively.

Input ends when T, H, and S are all -1. The number of datasets does not exceed 50.

output

For each dataset
On the first line, the hours, minutes, and seconds of the recordable time when the rest of the tape is recorded as standard, separated by half-width colons.
On the second line, the hours, minutes, and seconds of the recordable time when the rest of the tape is recorded three times are separated by half-width colons.
Please output.

Example

Input

1 30 0
-1 -1 -1

Output

00:30:00
01:30:00


p00206 Next Trip

You want to go on a trip with a friend. However, friends who have a habit of spending money cannot easily save travel expenses. I don't know when my friends will go on a trip if they continue their current lives. So, if you want to travel early, you decide to create a program to help your friends save in a planned manner.

If you have a friend's pocket money of M yen and the money you spend in that month is N yen, you will save (M --N) yen in that month. Create a program that inputs the monthly income and expenditure information M and N and outputs the number of months it takes for the savings amount to reach the travel cost L. However, if your savings do not reach your travel expenses after 12 months, print NA.

Input

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

L
M1 N1
M2 N2
::
M12 N12

The first line gives the travel cost L (1 ≤ L ≤ 1000000, integer). The next 12 lines are given the balance information for the i month, Mi, Ni (0 ≤ Mi, Ni ≤ 100000, Ni ≤ Mi, integer).

The number of datasets does not exceed 1000.

Output

For each input dataset, print the number of months it takes for your savings to reach your travel costs on a single line.

Example

Input

10000
5000 3150
5000 5000
0 0
5000 1050
5000 3980
5000 210
5000 5000
5000 5000
0 0
5000 2100
5000 2100
5000 2100
29170
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 70831
0

Output

6
NA

```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0206

"""
import sys
from sys import stdin
input = stdin.readline

def main(args):
    while True:
        L = int(input())
        if L == 0:
            break
        ans = 'NA'
        for i in range(1, 12+1):
            if ans == 'NA':
                M, N = map(int, input().split())
                L -= (M - N)
                if L <= 0:
                    ans = i
            else:
                _ = input()
        print(ans)

if __name__ == '__main__':
    main(sys.argv[1:])
```


p00365 Age Difference

A trick of fate caused Hatsumi and Taku to come to know each other. To keep the encounter in memory, they decided to calculate the difference between their ages. But the difference in ages varies depending on the day it is calculated. While trying again and again, they came to notice that the difference of their ages will hit a maximum value even though the months move on forever.

Given the birthdays for the two, make a program to report the maximum difference between their ages. The age increases by one at the moment the birthday begins. If the birthday coincides with the 29th of February in a leap year, the age increases at the moment the 1st of March arrives in non-leap years.

Input

The input is given in the following format.

y_1 m_1 d_1
y_2 m_2 d_2

The first and second lines provide Hatsumi’s and Taku’s birthdays respectively in year y_i (1 ≤ y_i ≤ 3000), month m_i (1 ≤ m_i ≤ 12), and day d_i (1 ≤ d_i ≤ Dmax) format. Where Dmax is given as follows:

* 28 when February in a non-leap year
* 29 when February in a leap-year
* 30 in April, June, September, and November
* 31 otherwise.

It is a leap year if the year represented as a four-digit number is divisible by 4. Note, however, that it is a non-leap year if divisible by 100, and a leap year if divisible by 400.

Output

Output the maximum difference between their ages.

Examples

Input

1999 9 9
2001 11 3

Output

3

Input

2008 2 29
2015 3 1

Output

8

```python
y1,m1,d1 = map(int, input().split())
y2,m2,d2 = map(int, input().split())

if y1 > y2 or (y1 == y2 and (m1 > m2 or ( m1 == m2 and d1 > d2 ))):
    y1, y2 = y2, y1
    m1, m2 = m2, m1
    d1, d2 = d2, d1

if m1 < m2 or (m1 == m2 and d1 < d2): print(y2 - y1 + 1)
else: print(y2 - y1)

```


p00720 Earth Observation with a Mobile Robot Team

A new type of mobile robot has been developed for environmental earth observation. It moves around on the ground, acquiring and recording various sorts of observational data using high precision sensors. Robots of this type have short range wireless communication devices and can exchange observational data with ones nearby. They also have large capacity memory units, on which they record data observed by themselves and those received from others.

Figure 1 illustrates the current positions of three robots A, B, and C and the geographic coverage of their wireless devices. Each circle represents the wireless coverage of a robot, with its center representing the position of the robot. In this figure, two robots A and B are in the positions where A can transmit data to B, and vice versa. In contrast, C cannot communicate with A or B, since it is too remote from them. Still, however, once B moves towards C as in Figure 2, B and C can start communicating with each other. In this manner, B can relay observational data from A to C. Figure 3 shows another example, in which data propagate among several robots instantaneously.

<image>
---
Figure 1: The initial configuration of three robots
<image>
---
Figure 2: Mobile relaying
<image>
---
Figure 3: Instantaneous relaying among multiple robots

As you may notice from these examples, if a team of robots move properly, observational data quickly spread over a large number of them. Your mission is to write a program that simulates how information spreads among robots. Suppose that, regardless of data size, the time necessary for communication is negligible.

Input

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

> N T R
>  nickname and travel route of the first robot
>  nickname and travel route of the second robot
>  ...
>  nickname and travel route of the N-th robot
>

The first line contains three integers N, T, and R that are the number of robots, the length of the simulation period, and the maximum distance wireless signals can reach, respectively, and satisfy that 1 <=N <= 100, 1 <= T <= 1000, and 1 <= R <= 10.

The nickname and travel route of each robot are given in the following format.

> nickname
>  t0 x0 y0
>  t1 vx1 vy1
>  t2 vx2 vy2
>  ...
>  tk vxk vyk
>

Nickname is a character string of length between one and eight that only contains lowercase letters. No two robots in a dataset may have the same nickname. Each of the lines following nickname contains three integers, satisfying the following conditions.

> 0 = t0 < t1 < ... < tk = T
>  -10 <= vx1, vy1, ..., vxk, vyk<= 10
>

A robot moves around on a two dimensional plane. (x0, y0) is the location of the robot at time 0. From time ti-1 to ti (0 < i <= k), the velocities in the x and y directions are vxi and vyi, respectively. Therefore, the travel route of a robot is piecewise linear. Note that it may self-overlap or self-intersect.

You may assume that each dataset satisfies the following conditions.

* The distance between any two robots at time 0 is not exactly R.
* The x- and y-coordinates of each robot are always between -500 and 500, inclusive.
* Once any robot approaches within R + 10-6 of any other, the distance between them will become smaller than R - 10-6 while maintaining the velocities.
* Once any robot moves away up to R - 10-6 of any other, the distance between them will become larger than R + 10-6 while maintaining the velocities.
* If any pair of robots mutually enter the wireless area of the opposite ones at time t and any pair, which may share one or two members with the aforementioned pair, mutually leave the wireless area of the opposite ones at time t', the difference between t and t' is no smaller than 10-6 time unit, that is, |t - t' | >= 10-6.

A dataset may include two or more robots that share the same location at the same time. However, you should still consider that they can move with the designated velocities.

The end of the input is indicated by a line containing three zeros.

Output

For each dataset in the input, your program should print the nickname of each robot that have got until time T the observational data originally acquired by the first robot at time 0. Each nickname should be written in a separate line in dictionary order without any superfluous characters such as leading or trailing spaces.

Example

Input

3 5 10
red
0 0 0
5 0 0
green
0 5 5
5 6 1
blue
0 40 5
5 0 0
3 10 5
atom
0 47 32
5 -10 -7
10 1 0
pluto
0 0 0
7 0 0
10 3 3
gesicht
0 25 7
5 -7 -2
10 -1 10
4 100 7
impulse
0 -500 0
100 10 1
freedom
0 -491 0
100 9 2
destiny
0 -472 0
100 7 4
strike
0 -482 0
100 8 3
0 0 0

Output

blue
green
red
atom
gesicht
pluto
freedom
impulse
strike

```python
from heapq import heappush, heappop
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
    N, T, R = map(int, readline().split())
    if N == T == R == 0:
        return False
    S = [None]*N
    TS = [None]*N
    for i in range(N):
        s = readline().strip()
        S[i] = s
        prv, x0, y0 = map(int, readline().split())
        r = []
        while prv != T:
            t, vx, vy = map(int, readline().split())
            r.append((prv, t, x0, y0, vx, vy))
            x0 += vx*(t - prv); y0 += vy*(t - prv)
            prv = t
        TS[i] = r
    INF = 10**18
    que = [(0, 0)]
    dist = [INF]*N
    dist[0] = 0
    while que:
        cost, v = heappop(que)
        if cost - dist[v] > 1e-6:
            continue
        k0 = 0
        T1 = TS[v]
        while 1:
            t0, t1, x0, y0, vx, vy = T1[k0]
            if t0 <= cost <= t1:
                break
            k0 += 1
        for w in range(N):
            if v == w or dist[w] < cost:
                continue
            k1 = k0
            k2 = 0
            T2 = TS[w]
            while 1:
                t0, t1, x0, y0, vx, vy = T2[k2]
                if t0 <= cost <= t1:
                    break
                k2 += 1
            while 1:
                p0, p1, x0, y0, vx0, vy0 = T1[k1]
                q0, q1, x1, y1, vx1, vy1 = T2[k2]
                t0 = max(p0, q0, cost); t1 = min(p1, q1)
                if dist[w] <= t0:
                    break
                a0 = (vx0 - vx1)
                a1 = (x0 - p0*vx0) - (x1 - q0*vx1)
                b0 = (vy0 - vy1)
                b1 = (y0 - p0*vy0) - (y1 - q0*vy1)
                A = a0**2 + b0**2
                B = 2*(a0*a1 + b0*b1)
                C = a1**2 + b1**2 - R**2
                if A == 0:
                    assert B == 0
                    if C <= 0:
                        e = t0
                        if e < dist[w]:
                            dist[w] = e
                            heappush(que, (e, w))
                        break
                else:
                    D = B**2 - 4*A*C
                    if D >= 0:
                        s0 = (-B - D**.5) / (2*A)
                        s1 = (-B + D**.5) / (2*A)
                        if t0 <= s1 and s0 <= t1:
                            e = max(t0, s0)
                            if e < dist[w]:
                                dist[w] = e
                                heappush(que, (e, w))
                            break
                if p1 < q1:
                    k1 += 1
                elif p1 > q1:
                    k2 += 1
                elif p1 == T:
                    break
                else:
                    k1 += 1; k2 += 1
    ans = []
    for i in range(N):
        if dist[i] < INF:
            ans.append(S[i])
    ans.sort()
    for e in ans:
        write("%s\n" % e)
    return True
while solve():
    ...

```


p00991 Grid

Two coordinates (a1, a2) and (b1, b2) on a two-dimensional grid of r × c are given. The cost of moving from a cell (e, f) to one of the cells (e + 1, f), (e-1, f), (e, f + 1), (e, f-1) is 1. And. You can also move between (e, c-1) and (e, 0), and between (r-1, f) and (0, f) at a cost of 1. At this time, find the number of routes that can be moved from the first coordinate to the second coordinate at the shortest cost.

Input

The input is given in the following format.

r c a1 a2 b1 b2

Input meets the following constraints
1 ≤ r, c ≤ 1,000
0 ≤ a1, b1 <r
0 ≤ a2, b2 <c

Output

Output the remainder of the answer value divided by 100,000,007.

Examples

Input

4 4 0 0 3 3

Output

2

Input

4 4 0 0 1 1

Output

2

Input

2 3 0 0 1 2

Output

4

Input

500 500 0 0 200 200

Output

34807775

```python
# Edit: 2014/09/17
# Lang: Python3
# Time: 00.04s

from math import factorial

if __name__ == "__main__":
    r, c, ar, ac, br, bc = map(int, input().strip("\n").split(" "))
    maxans = 100000007  # 100,000,007

    # tate Row
    dr = min(abs(br - ar), r - abs(br - ar))
    if 2 * dr == r:
        gainr = 2
    else:
        gainr = 1

    # yoko Column
    dc = min(abs(bc - ac), c - abs(bc - ac))
    if 2 * dc == c:
        gainc = 2
    else:
        gainc = 1

    ans = factorial(dr + dc) // factorial(dr) // factorial(dc) * gainr * gainc

    print(ans % maxans)
```


p01422 Beautiful Currency

KM country has N kinds of coins and each coin has its value a_i.

The king of the country, Kita_masa, thought that the current currency system is poor, and he decided to make it beautiful by changing the values of some (possibly no) coins.

A currency system is called beautiful if each coin has an integer value and the (i+1)-th smallest value is divisible by the i-th smallest value for all i (1 \leq i \leq N-1).

For example, the set {1, 5, 10, 50, 100, 500} is considered as a beautiful system, while the set {1, 5, 10, 25, 50, 100} is NOT, because 25 is not divisible by 10.

Since changing the currency system may confuse citizens, the king, Kita_masa, wants to minimize the maximum value of the confusion ratios. Here, the confusion ratio for the change in the i-th coin is defined as |a_i - b_i| / a_i, where a_i and b_i is the value of i-th coin before and after the structure changes, respectively.

Note that Kita_masa can change the value of each existing coin, but he cannot introduce new coins nor eliminate existing coins. After the modification, the values of two or more coins may coincide.

Input

Each dataset contains two lines. The first line contains a single integer, N, and the second line contains N integers, {a_i}.

You may assume the following constraints:

1 \leq N \leq 20

1 \leq a_1 \lt a_2 \lt... \lt a_N \lt 10^5

Output

Output one number that represents the minimum of the maximum value of the confusion ratios. The value may be printed with an arbitrary number of decimal digits, but may not contain an absolute error greater than or equal to 10^{-8}.

Examples

Input

3
6 11 12

Output

0.090909090909

Input

3
6 11 24

Output

0.090909090909

Input

3
6 11 30

Output

0.166666666667

```python
# coding:utf-8

import sys

input = sys.stdin.readline
INF = float('inf')
MOD = 10 ** 9 + 7

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

def solve(N):
    A = inpl()
    dp = [INF] * (A[0] * 2)
    for i in range(A[0]//2, A[0]*2):
        dp[i] = abs(i - A[0]) / A[0]  # A[0]の価格を変えたときのconfusion ratio

    for i in range(N-1):
        a1 = A[i + 1]
        nn = a1 * 2
        ndp = [INF] * nn  # ndp[A[i+1]の変更後の価値] = confusion ratioの最小値
        for j in range(1, len(dp)):
            if dp[j] == INF:
                continue

            t = dp[j]
            for k in range(j, nn, j):
                u = abs(a1 - k) / a1
                if u < t:  # A[i]とA[i+1]でconfusion ratioの大きい方をndpと比較
                    u = t
                if ndp[k] > u:  # A[1]~A[i+1]まで帳尻を合わせたときのconfusion ratioの最小値を格納
                    ndp[k] = u

        dp = ndp

    return '{:0.12f}'.format(min(dp))

N = int(input())
if N != 0:
    print(solve(N))

```


p02298 Is-Convex

For a given polygon g, print "1" if g is a convex polygon, "0" otherwise. Here, in a convex polygon, all interior angles are less than or equal to 180 degrees.

g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon.

Constraints

* 3 ≤ n ≤ 100
* -10000 ≤ xi, yi ≤ 10000
* No point of the polygon will occur more than once.
* Two sides of the polygon can intersect only at a common endpoint.

Input

g is given by coordinates of the points p1,..., pn in the following format:

n
x1 y1
x2 y2
:
xn yn

The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them.

Output

Print "1" or "0" in a line.

Examples

Input

4
0 0
3 1
2 3
0 3

Output

1

Input

5
0 0
2 0
1 1
2 2
0 2

Output

0

```python
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

###########################
#          幾何
###########################
def sgn(a):
    if a < -eps: return -1
    if a >  eps: return  1
    return 0

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        pass

    def tolist(self):
        return [self.x,self.y]

    def __add__(self,p):
        return Point(self.x+p.x, self.y+p.y)
    def __iadd__(self,p):
        return self + p

    def __sub__(self,p):
        return Point(self.x - p.x, self.y - p.y)
    def __isub__(self,p):
        return self - p

    def __truediv__(self,n):
        return Point(self.x/n, self.y/n)
    def __itruediv__(self,n):
        return self / n

    def __mul__(self,n):
        return Point(self.x*n, self.y*n)
    def __imul__(self,n):
        return self * n

    def __lt__(self,other):
        tmp = sgn(self.x - other.x)
        if tmp != 0:
            return tmp < 0
        else:
            return sgn(self.y - other.y) < 0

    def __eq__(self,other):
        return sgn(self.x - other.x) == 0 and sgn(self.y - other.y) == 0

    def abs(self):
        return math.sqrt(self.x**2+self.y**2)

    def dot(self,p):
        return self.x * p.x + self.y*p.y

    def det(self,p):
        return self.x * p.y - self.y*p.x

    def arg(self,p):
        return math.atan2(y,x)

# 点の進行方向 a -> b -> c
def iSP(a,b,c):
    tmp = sgn((b-a).det(c-a))
    if tmp > 0:   return 1   # 左に曲がる場合
    elif tmp < 0: return -1  # 右に曲がる場合
    else: # まっすぐ
        if sgn((b-a).dot(c-a)) < 0: return -2 # c-a-b の順
        if sgn((a-b).dot(c-b)) < 0: return  2 # a-b-c の順
        return 0 # a-c-bの順

# ab,cd の直線交差
def isToleranceLine(a,b,c,d):
    if sgn((b-a).det(c-d)) != 0: return 1 # 交差する
    else:
        if sgn((b-a).det(c-a)) != 0: return 0 # 平行
        else: return -1 # 同一直線

# ab,cd の線分交差 重複，端点での交差もTrue
def isToleranceSegline(a,b,c,d):
    return sgn(iSP(a,b,c)*iSP(a,b,d))<=0 and sgn(iSP(c,d,a)*iSP(c,d,b)) <= 0

# 直線ab と 直線cd の交点 (存在する前提)
def Intersection(a,b,c,d):
    tmp1 = (b-a)*((c-a).det(d-c))
    tmp2 = (b-a).det(d-c)
    return a+(tmp1/tmp2)

# 直線ab と 点c の距離
def DistanceLineToPoint(a,b,c):
    return abs(((c-a).det(b-a))/((b-a).abs()))

# 線分ab と 点c の距離
def DistanceSeglineToPoint(a,b,c):
    if sgn((b-a).dot(c-a)) < 0: # <cab が鈍角
        return (c-a).abs()
    if sgn((a-b).dot(c-b)) < 0: # <cba が鈍角
        return (c-b).abs()
    return DistanceLineToPoint(a,b,c)

# 直線ab への 点c からの垂線の足
def Vfoot(a,b,c):
    d = c + Point((b-a).y,-(b-a).x)
    return Intersection(a,b,c,d)

# 多角形の面積
def PolygonArea(Plist):
    #Plist = ConvexHull(Plist)
    L = len(Plist)
    S = 0
    for i in range(L):
        tmpS = (Plist[i-1].det(Plist[i]))/2
        S += tmpS
    return S

# 多角形の重心
def PolygonG(Plist):
    Plist = ConvexHull(Plist)
    L = len(Plist)
    S = 0
    G = Point(0,0)
    for i in range(L):
        tmpS = (Plist[i-1].det(Plist[i]))/2
        S += tmpS
        G += (Plist[i-1]+Plist[i])/3*tmpS
    return G/S

# 凸法
def ConvexHull(Plist):
    Plist.sort()
    L = len(Plist)
    qu = deque([])
    quL = 0
    for p in Plist:
        while quL >= 2 and iSP(qu[quL-2],qu[quL-1],p) == 1:
            qu.pop()
            quL -= 1
        qu.append(p)
        quL += 1

    qd = deque([])
    qdL = 0
    for p in Plist:
        while qdL >= 2 and iSP(qd[qdL-2],qd[qdL-1],p) == -1:
            qd.pop()
            qdL -= 1
        qd.append(p)
        qdL += 1

    qd.pop()
    qu.popleft()
    hidari = list(qd) + list(reversed(qu)) # 左端開始，左回りPlist
    return hidari

N = int(input())
Plyst = [Point(*inpl()) for _ in range(N)]
Plyst2 = ConvexHull(Plyst)

L1 = [tuple(p.tolist()) for p in Plyst]
L2 = [tuple(p.tolist()) for p in Plyst2]

if len(list(set(L1))) != len(list(set(L2))):
    print(0)
else:
    print(1)

```


p02445 Swap

Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and swap specified elements by a list of the following operation:

* swapRange($b, e, t$): For each integer $k$ ($0 \leq k < (e - b)$, swap element $(b + k)$ and element $(t + k)$.

Constraints

* $1 \leq n \leq 1,000$
* $-1,000,000,000 \leq a_i \leq 1,000,000,000$
* $1 \leq q \leq 1,000$
* $0 \leq b_i < e_i \leq n$
* $0 \leq t_i < t_i + (e_i - b_i) \leq n$
* Given swap ranges do not overlap each other

Input

The input is given in the following format.

$n$
$a_0 \; a_1 \; ...,\; a_{n-1}$
$q$
$b_1 \; e_1 \; t_1$
$b_2 \; e_2 \; t_2$
:
$b_{q} \; e_{q} \; t_{q}$

In the first line, $n$ (the number of elements in $A$) is given. In the second line, $a_i$ (each element in $A$) are given. In the third line, the number of queries $q$ is given and each query is given by three integers $b_i \; e_i \; t_i$ in the following $q$ lines.

Output

Print all elements of $A$ in a line after performing the given operations. Put a single space character between adjacency elements and a newline at the end of the last element.

Example

Input

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

Output

1 8 9 10 5 6 7 2 3 4 11

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

q = int(input())
for _ in range(q):
    b, e, t = map(int, input().split())
    for i in range(e-b):
        num[b+i], num[t+i] = num[t+i], num[b+i]

print(' '.join(str(n) for n in num))

```


1012_B. Chemical table

Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.

Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).

<image>

Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.

Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.

Input

The first line contains three integers n, m, q (1 ≤ n, m ≤ 200 000; 0 ≤ q ≤ min(n·m, 200 000)), the chemical table dimensions and the number of elements scientists already have.

The following q lines contain two integers ri, ci (1 ≤ ri ≤ n, 1 ≤ ci ≤ m), each describes an element that scientists already have. All elements in the input are different.

Output

Print the minimal number of elements to be purchased.

Examples

Input

2 2 3
1 2
2 2
2 1

Output

0

Input

1 5 3
1 3
1 1
1 5

Output

2

Input

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

Output

1

Note

For each example you have a picture which illustrates it.

The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.

The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (the optimal solution should minimize the number of red circles). Blue dashed circles are elements that can be produced with nuclear fusion. They are numbered in order in which they can be produced.

Test 1

We can use nuclear fusion and get the element from three other samples, so we don't need to purchase anything.

<image>

Test 2

We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.

<image>

Test 3

There are several possible solutions. One of them is illustrated below.

Note that after purchasing one element marked as red it's still not possible to immidiately produce the middle element in the bottom row (marked as 4). So we produce the element in the left-top corner first (marked as 1), and then use it in future fusions.

<image>

```python
class UnionFind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [0]*n

    def Find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.Find(self.par[x])
            return self.par[x]

    def Unite(self, x, y):
        x = self.Find(x)
        y = self.Find(y)

        if x != y:
            if self.rank[x] < self.rank[y]:
                self.par[y] += self.par[x]
                self.par[x] = y
            else:
                self.par[x] += self.par[y]
                self.par[y] = x
                if self.rank[x] == self.rank[y]:
                    self.rank[x] += 1

    def Same(self, x, y):
        return self.Find(x) == self.Find(y)

    def Size(self, x):
        return -self.par[self.Find(x)]

import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

n, m, q = map(int, input().split())
uf = UnionFind(n+m)
for i in range(q):
    r, c = map(int, input().split())
    r, c = r-1, c-1
    uf.Unite(r, c+n)

S = set()
for i in range(n+m):
    S.add(uf.Find(i))
print(len(S)-1)

```


1037_B. Reach Median

You are given an array a of n integers and an integer s. It is guaranteed that n is odd.

In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s.

The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array 6, 5, 8 is equal to 6, since if we sort this array we will get 5, 6, 8, and 6 is located on the middle position.

Input

The first line contains two integers n and s (1≤ n≤ 2⋅ 10^5-1, 1≤ s≤ 10^9) — the length of the array and the required value of median.

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

It is guaranteed that n is odd.

Output

In a single line output the minimum number of operations to make the median being equal to s.

Examples

Input

3 8
6 5 8

Output

2

Input

7 20
21 15 12 11 20 19 12

Output

6

Note

In the first sample, 6 can be increased twice. The array will transform to 8, 5, 8, which becomes 5, 8, 8 after sorting, hence the median is equal to 8.

In the second sample, 19 can be increased once and 15 can be increased five times. The array will become equal to 21, 20, 12, 11, 20, 20, 12. If we sort this array we get 11, 12, 12, 20, 20, 20, 21, this way the median is 20.

```python

# -*- coding: utf-8 -*-
# @Date    : 2018-09-03 08:46:01
# @Author  : raj lath (oorja.halt@gmail.com)
# @Link    : http://codeforces.com/contest/1037/problem/B
# @Version : 1.0.0

import os
from sys import stdin

max_val=int(10e12)
min_val=int(-10e12)

def read_int()     : return int(stdin.readline())
def read_ints()    : return [int(x) for x in stdin.readline().split()]
def read_str()     : return input()
def read_strs()    : return [x for x in stdin.readline().split()]
def read_str_list(): return [x for x in stdin.readline().split().split()]

nb_elemets, value_needed = read_ints()
elements = sorted(read_ints())
mid = nb_elemets//2
ans = abs(elements[mid] - value_needed)
ans += sum( max(0, (a - value_needed)) for a in elements[:mid] )
ans += sum( max(0, (value_needed - a)) for a in elements[mid+1:] )
print(ans)

```


105_C. Item World

Each item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res).

Each item belongs to one class. In this problem we will only consider three of such classes: weapon, armor, orb.

Besides, there's a whole new world hidden inside each item. We can increase an item's level travelling to its world. We can also capture the so-called residents in the Item World

Residents are the creatures that live inside items. Each resident gives some bonus to the item in which it is currently located. We will only consider residents of types: gladiator (who improves the item's atk), sentry (who improves def) and physician (who improves res).

Each item has the size parameter. The parameter limits the maximum number of residents that can live inside an item. We can move residents between items. Within one moment of time we can take some resident from an item and move it to some other item if it has a free place for a new resident. We cannot remove a resident from the items and leave outside — any of them should be inside of some item at any moment of time.

Laharl has a certain number of items. He wants to move the residents between items so as to equip himself with weapon, armor and a defensive orb. The weapon's atk should be largest possible in the end. Among all equipping patterns containing weapon's maximum atk parameter we should choose the ones where the armor’s def parameter is the largest possible. Among all such equipment patterns we should choose the one where the defensive orb would have the largest possible res parameter. Values of the parameters def and res of weapon, atk and res of armor and atk and def of orb are indifferent for Laharl.

Find the optimal equipment pattern Laharl can get.

Input

The first line contains number n (3 ≤ n ≤ 100) — representing how many items Laharl has.

Then follow n lines. Each line contains description of an item. The description has the following form: "name class atk def res size" — the item's name, class, basic attack, defense and resistance parameters and its size correspondingly.

  * name and class are strings and atk, def, res and size are integers.
  * name consists of lowercase Latin letters and its length can range from 1 to 10, inclusive.
  * class can be "weapon", "armor" or "orb".
  * 0 ≤ atk, def, res ≤ 1000.
  * 1 ≤ size ≤ 10.

It is guaranteed that Laharl has at least one item of each class.

The next line contains an integer k (1 ≤ k ≤ 1000) — the number of residents.

Then k lines follow. Each of them describes a resident. A resident description looks like: "name type bonus home" — the resident's name, his type, the number of points the resident adds to the item's corresponding parameter and the name of the item which currently contains the resident.

  * name, type and home are strings and bonus is an integer.
  * name consists of lowercase Latin letters and its length can range from 1 to 10, inclusive.
  * type may be "gladiator", "sentry" or "physician".
  * 1 ≤ bonus ≤ 100.

It is guaranteed that the number of residents in each item does not exceed the item's size.

The names of all items and residents are pairwise different.

All words and numbers in the input are separated by single spaces.

Output

Print on the first line the name of the weapon in the optimal equipping pattern; then print the number of residents the weapon contains; then print the residents' names.

Print on the second and third lines in the same form the names of the armor and defensive orb as well as the residents they contain.

Use single spaces for separation.

If there are several possible solutions, print any of them.

Examples

Input

4
sword weapon 10 2 3 2
pagstarmor armor 0 15 3 1
iceorb orb 3 2 13 2
longbow weapon 9 1 2 1
5
mike gladiator 5 longbow
bobby sentry 6 pagstarmor
petr gladiator 7 iceorb
teddy physician 6 sword
blackjack sentry 8 sword

Output

sword 2 petr mike
pagstarmor 1 blackjack
iceorb 2 teddy bobby

Input

4
sword weapon 10 2 3 2
pagstarmor armor 0 15 3 1
iceorb orb 3 2 13 2
longbow weapon 9 1 2 1
6
mike gladiator 5 longbow
bobby sentry 6 pagstarmor
petr gladiator 7 iceorb
teddy physician 6 sword
blackjack sentry 8 sword
joe physician 6 iceorb

Output

longbow 1 mike
pagstarmor 1 bobby
iceorb 2 petr joe

Note

In the second sample we have no free space inside the items, therefore we cannot move the residents between them.

```python
# written with help of failed tests
def searchBest(iType, number, rType, countResidents):
    global items, equipped
    best = 0
    ret = None
    for item, params in items.items():
        if params[0] == iType:
            val = int(params[number])
            if countResidents:
                for resid in equipped[item]:
                    if resid[1] == rType:
                        val += int(resid[2])
            if val > best:
                best = val
                ret = item
    return ret

def printItem(item):
    global equipped
    print(item, len(equipped[item]), ' '.join([x[0] for x in equipped[item]]))

def searchFor(iType, number, might):
    global items, equipped, liesIn
    pSum = [0]
    for x in might:
        pSum.append(pSum[-1] + int(x[2]))
    while len(pSum) < 11:
        pSum.append(pSum[-1])

    bestVal = 0
    for item, params in items.items():
        if params[0] == iType:
            val = int(params[number]) + pSum[int(params[4])]
            if val > bestVal:
                bestVal = val

    for item, params in items.items():
        if params[0] == iType:
            val = int(params[number]) + pSum[int(params[4])]
            if val == bestVal:
                for i in range(min(int(params[4]), len(might))):
                    want = might[i]
                    equipped[liesIn[want[0]]].remove(want)
                    liesIn[want[0]] = item

                    if len(equipped[item]) == int(params[4]):
                        rm = equipped[item][0]
                        liesIn[rm[0]] = want[3]
                        equipped[want[3]] = [rm] + equipped[want[3]]
                        equipped[item].remove(rm)
                    equipped[item].append(want)

                return item

def rel(item):
    global liesIn, equipped, items
    while len(equipped[item]) > int(items[item][4]):
        toDelete = equipped[item][0]
        for other in items:
            if len(equipped[other]) < int(items[other][4]):
                liesIn[toDelete[0]] = other
                equipped[other].append(toDelete)
                break
        equipped[item] = equipped[item][1:]

n = int(input())
items = dict()
equipped = dict()
for i in range(n):
    t = tuple(input().split())
    items[t[0]] = t[1:]
    equipped[t[0]] = []

k = int(input())
residents = [None for i in range(k)]
glads = dict()
liesIn = dict()
for i in range(k):
    residents[i] = tuple(input().split())
    equipped[residents[i][3]] = equipped.get(residents[i][3], []) + [residents[i]]
    liesIn[residents[i][0]] = residents[i][3]

canSwap = False
for name, val in equipped.items():
    if len(val) < int(items[name][4]):
        canSwap = True

if canSwap:
    glads = sorted([x for x in residents if x[1] == 'gladiator'], key = lambda x: -int(x[2]))
    sentries = sorted([x for x in residents if x[1] == 'sentry'], key = lambda x: -int(x[2]))
    phys = sorted([x for x in residents if x[1] == 'physician'], key = lambda x: -int(x[2]))

    wp = searchFor('weapon', 1, glads)
    ar = searchFor('armor', 2, sentries)
    orb = searchFor('orb', 3, phys)
    rel(wp)
    rel(ar)
    rel(orb)
    printItem(wp)
    printItem(ar)
    printItem(orb)
else:
    printItem(searchBest('weapon', 1, 'gladiator', True))
    printItem(searchBest('armor', 2, 'sentry', True))
    printItem(searchBest('orb', 3, 'physician', True))

```


1081_D. Maximum Distance

Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.

You are given a connected undirected graph with n vertices and m weighted edges. There are k special vertices: x_1, x_2, …, x_k.

Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them.

For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.

The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.

Input

The first line contains three integers n, m and k (2 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 10^5) — the number of vertices, the number of edges and the number of special vertices.

The second line contains k distinct integers x_1, x_2, …, x_k (1 ≤ x_i ≤ n).

Each of the following m lines contains three integers u, v and w (1 ≤ u,v ≤ n, 1 ≤ w ≤ 10^9), denoting there is an edge between u and v of weight w. The given graph is undirected, so an edge (u, v) can be used in the both directions.

The graph may have multiple edges and self-loops.

It is guaranteed, that the graph is connected.

Output

The first and only line should contain k integers. The i-th integer is the distance between x_i and the farthest special vertex from it.

Examples

Input

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

Output

2 2

Input

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

Output

3 3 3

Note

In the first example, the distance between vertex 1 and 2 equals to 2 because one can walk through the edge of weight 2 connecting them. So the distance to the farthest node for both 1 and 2 equals to 2.

In the second example, one can find that distance between 1 and 2, distance between 1 and 3 are both 3 and the distance between 2 and 3 is 2.

The graph may have multiple edges between and self-loops, as in the first example.

```python
"""
@author: phamv
"""
####Function Definition
def find(x):
    while f[x] != x :
        f[x] = f[f[x]]
        x = f[x]
    return x

def merge(u, v) :
    u, v = map(find, (u, v))
    f[u] = v;
    if u == v:
        return False
    ret = s[u] > 0 and s[v] > 0
    s[v] += s[u]
    return ret

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

n, m, k = map(int, input().split())
x = list(map(int, input().split()))
lst = list()
for i in range(m):
    lst.append(tuple(map(int, input().split())))
lst.sort(key = lambda x: x[2])

f = list(range(n + 1))
s = [0] * (n + 1)

for j in x:
    s[j] += 1

for h in lst:
    if merge(h[0], h[1]):
        answer = h[2]

print(*[answer]*k)
```


1129_A2. Toy Train

Alice received a set of Toy Train™ from Bob. It consists of one train and a connected railway network of n stations, enumerated from 1 through n. The train occupies one station at a time and travels around the network of stations in a circular manner. More precisely, the immediate station that the train will visit after station i is station i+1 if 1 ≤ i < n or station 1 if i = n. It takes the train 1 second to travel to its next station as described.

Bob gave Alice a fun task before he left: to deliver m candies that are initially at some stations to their independent destinations using the train. The candies are enumerated from 1 through m. Candy i (1 ≤ i ≤ m), now at station a_i, should be delivered to station b_i (a_i ≠ b_i).

<image> The blue numbers on the candies correspond to b_i values. The image corresponds to the 1-st example.

The train has infinite capacity, and it is possible to load off any number of candies at a station. However, only at most one candy can be loaded from a station onto the train before it leaves the station. You can choose any candy at this station. The time it takes to move the candies is negligible.

Now, Alice wonders how much time is needed for the train to deliver all candies. Your task is to find, for each station, the minimum time the train would need to deliver all the candies were it to start from there.

Input

The first line contains two space-separated integers n and m (2 ≤ n ≤ 5 000; 1 ≤ m ≤ 20 000) — the number of stations and the number of candies, respectively.

The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n; a_i ≠ b_i) — the station that initially contains candy i and the destination station of the candy, respectively.

Output

In the first and only line, print n space-separated integers, the i-th of which is the minimum time, in seconds, the train would need to deliver all the candies were it to start from station i.

Examples

Input

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

Output

10 9 10 10 9

Input

2 3
1 2
1 2
1 2

Output

5 6

Note

Consider the second sample.

If the train started at station 1, the optimal strategy is as follows.

  1. Load the first candy onto the train.
  2. Proceed to station 2. This step takes 1 second.
  3. Deliver the first candy.
  4. Proceed to station 1. This step takes 1 second.
  5. Load the second candy onto the train.
  6. Proceed to station 2. This step takes 1 second.
  7. Deliver the second candy.
  8. Proceed to station 1. This step takes 1 second.
  9. Load the third candy onto the train.
  10. Proceed to station 2. This step takes 1 second.
  11. Deliver the third candy.

Hence, the train needs 5 seconds to complete the tasks.

If the train were to start at station 2, however, it would need to move to station 1 before it could load the first candy, which would take one additional second. Thus, the answer in this scenario is 5+1 = 6 seconds.

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

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

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")

#-------------------game starts now-----------------------------------------------------
mii=lambda:map(int,input().split())

n,m=mii()
a=[0 for _ in range(n)]
c=[123456 for _ in range(n)]
for _ in range(m):
    u,v=mii()
    u%=n
    v%=n
    if v<u: v+=n
    a[u]+=1
    if c[u]>v: c[u]=v

ans=[]
for i in list(range(1,n))+[0]:
    out=0
    for j in range(i,n):
        if not a[j]: continue
        tmp=(j-i)+(a[j]-1)*n+(c[j]-j)
        out=max(out,tmp)
        #print(1,i,j,tmp)
    for j in range(i):
        if not a[j]: continue
        tmp=(j+n-i)+(a[j]-1)*n+(c[j]-j)
        out=max(out,tmp)
        #print(2,i,j,tmp)
    ans.append(out)
print(" ".join(map(str,ans)))
```


1149_B. Three Religions

During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.

The Word of Universe is a long word containing the lowercase English characters only. At each moment of time, each of the religion beliefs could be described by a word consisting of lowercase English characters.

The three religions can coexist in peace if their descriptions form disjoint subsequences of the Word of Universe. More formally, one can paint some of the characters of the Word of Universe in three colors: 1, 2, 3, so that each character is painted in at most one color, and the description of the i-th religion can be constructed from the Word of Universe by removing all characters that aren't painted in color i.

The religions however evolve. In the beginning, each religion description is empty. Every once in a while, either a character is appended to the end of the description of a single religion, or the last character is dropped from the description. After each change, determine if the religions could coexist in peace.

Input

The first line of the input contains two integers n, q (1 ≤ n ≤ 100 000, 1 ≤ q ≤ 1000) — the length of the Word of Universe and the number of religion evolutions, respectively. The following line contains the Word of Universe — a string of length n consisting of lowercase English characters.

Each of the following line describes a single evolution and is in one of the following formats:

  * + i c (i ∈ \{1, 2, 3\}, c ∈ \{a, b, ..., z\}: append the character c to the end of i-th religion description.
  * - i (i ∈ \{1, 2, 3\}) – remove the last character from the i-th religion description. You can assume that the pattern is non-empty.

You can assume that no religion will have description longer than 250 characters.

Output

Write q lines. The i-th of them should be YES if the religions could coexist in peace after the i-th evolution, or NO otherwise.

You can print each character in any case (either upper or lower).

Examples

Input

6 8
abdabc
+ 1 a
+ 1 d
+ 2 b
+ 2 c
+ 3 a
+ 3 b
+ 1 c
- 2

Output

YES
YES
YES
YES
YES
YES
NO
YES

Input

6 8
abbaab
+ 1 a
+ 2 a
+ 3 a
+ 1 b
+ 2 b
+ 3 b
- 1
+ 2 z

Output

YES
YES
YES
YES
YES
NO
YES
NO

Note

In the first example, after the 6th evolution the religion descriptions are: ad, bc, and ab. The following figure shows how these descriptions form three disjoint subsequences of the Word of Universe:

<image>

```python
n, q = map(int, input().split())
s = '!' + input()

nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
    c = ord(s[i + 1]) - 97
    for j in range(26):
        nxt[j][i] = nxt[j][i + 1]
    nxt[c][i] = i + 1

w = [[-1], [-1], [-1]]
idx = lambda i, j, k: i * 65536 + j * 256 + k
dp = [0] * (256 * 256 * 256)
def calc(fix=None):
    r = list(map(range, (len(w[0]), len(w[1]), len(w[2]))))
    if fix is not None: r[fix] = range(len(w[fix]) - 1, len(w[fix]))
    for i in r[0]:
        for j in r[1]:
            for k in r[2]:
                dp[idx(i, j, k)] = min(nxt[w[0][i]][dp[idx(i - 1, j, k)]] if i else n + 1,
                                       nxt[w[1][j]][dp[idx(i, j - 1, k)]] if j else n + 1,
                                       nxt[w[2][k]][dp[idx(i, j, k - 1)]] if k else n + 1)
                if i == j == k == 0: dp[idx(i, j, k)] = 0

out = []
for _ in range(q):
    t, *r = input().split()
    if t == '+':
        i, c = int(r[0]) - 1, ord(r[1]) - 97
        w[i].append(c)
        calc(i)
    else:
        i = int(r[0]) - 1
        w[i].pop()
    req = dp[idx(len(w[0]) - 1, len(w[1]) - 1, len(w[2]) - 1)]
    out.append('YES' if req <= n else 'NO')

print(*out, sep='\n')
```


1189_A. Keanu Reeves

After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.

Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For example, 1, 101, 0000 are good, while 01, 1001, and 111000 are not good.

We are given a string s of length n consisting of only zeroes and ones. We need to cut s into minimal possible number of substrings s_1, s_2, …, s_k such that all of them are good. More formally, we have to find minimal by number of strings sequence of good strings s_1, s_2, …, s_k such that their concatenation (joining) equals s, i.e. s_1 + s_2 + ... + s_k = s.

For example, cuttings 110010 into 110 and 010 or into 11 and 0010 are valid, as 110, 010, 11, 0010 are all good, and we can't cut 110010 to the smaller number of substrings as 110010 isn't good itself. At the same time, cutting of 110010 into 1100 and 10 isn't valid as both strings aren't good. Also, cutting of 110010 into 1, 1, 0010 isn't valid, as it isn't minimal, even though all 3 strings are good.

Can you help Keanu? We can show that the solution always exists. If there are multiple optimal answers, print any.

Input

The first line of the input contains a single integer n (1≤ n ≤ 100) — the length of the string s.

The second line contains the string s of length n consisting only from zeros and ones.

Output

In the first line, output a single integer k (1≤ k) — a minimal number of strings you have cut s into.

In the second line, output k strings s_1, s_2, …, s_k separated with spaces. The length of each string has to be positive. Their concatenation has to be equal to s and all of them have to be good.

If there are multiple answers, print any.

Examples

Input

1
1

Output

1
1

Input

2
10

Output

2
1 0

Input

6
100011

Output

2
100 011

Note

In the first example, the string 1 wasn't cut at all. As it is good, the condition is satisfied.

In the second example, 1 and 0 both are good. As 10 isn't good, the answer is indeed minimal.

In the third example, 100 and 011 both are good. As 100011 isn't good, the answer is indeed minimal.


1208_A. XORinacci

Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:

  * f(0) = a;
  * f(1) = b;
  * f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).

You are given three integers a, b, and n, calculate f(n).

You have to answer for T independent test cases.

Input

The input contains one or more independent test cases.

The first line of input contains a single integer T (1 ≤ T ≤ 10^3), the number of test cases.

Each of the T following lines contains three space-separated integers a, b, and n (0 ≤ a, b, n ≤ 10^9) respectively.

Output

For each test case, output f(n).

Example

Input

3
3 4 2
4 5 0
325 265 1231232

Output

7
4
76

Note

In the first example, f(2) = f(0) ⊕ f(1) = 3 ⊕ 4 = 7.

```python
import sys
from collections import defaultdict as dd
from collections import deque
from functools import *
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations ,product

def eprint(*args):
    print(*args, file=sys.stderr)
zz=1

#sys.setrecursionlimit(10**6)
if zz:
	input=sys.stdin.readline
else:
	sys.stdin=open('input.txt', 'r')
	sys.stdout=open('all.txt','w')
def inc(d,c):
	d[c]=d[c]+1 if c in d else 1
def bo(i):
	return ord(i)-ord('A')
def li():
	return [int(xx) for xx in input().split()]
def fli():
	return [float(x) for x in input().split()]
def comp(a,b):
	if(a>b):
		return 2
	return 2 if a==b else 0
def gi():
	return [xx for xx in input().split()]
def fi():
	return int(input())
def pro(a):
	return reduce(lambda a,b:a*b,a)
def swap(a,i,j):
	a[i],a[j]=a[j],a[i]
def si():
	return list(input().rstrip())
def mi():
	return 	map(int,input().split())
def gh():
	sys.stdout.flush()
def isvalid(i,j):
	return 0<=i<n and 0<=j<n
def bo(i):
	return ord(i)-ord('a')
def graph(n,m):
	for i in range(m):
		x,y=mi()
		a[x].append(y)
		a[y].append(x)

t=fi()

while t>0:
	t-=1
	a,b,n=mi()
	n+=1
	if n%3==0:
		print(a^b)
	elif n%3==1:
		print(a)
	else:
		print(b)

```


1227_A. Math Problem

Your math teacher gave you the following problem:

There are n segments on the x-axis, [l_1; r_1], [l_2; r_2], …, [l_n; r_n]. The segment [l; r] includes the bounds, i.e. it is a set of such x that l ≤ x ≤ r. The length of the segment [l; r] is equal to r - l.

Two segments [a; b] and [c; d] have a common point (intersect) if there exists x that a ≤ x ≤ b and c ≤ x ≤ d. For example, [2; 5] and [3; 10] have a common point, but [5; 6] and [1; 4] don't have.

You should add one segment, which has at least one common point with each of the given segments and as short as possible (i.e. has minimal length). The required segment can degenerate to be a point (i.e a segment with length zero). The added segment may or may not be among the given n segments.

In other words, you need to find a segment [a; b], such that [a; b] and every [l_i; r_i] have a common point for each i, and b-a is minimal.

Input

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

The first line of each test case contains one integer n (1 ≤ n ≤ 10^{5}) — the number of segments. The following n lines contain segment descriptions: the i-th of them contains two integers l_i,r_i (1 ≤ l_i ≤ r_i ≤ 10^{9}).

The sum of all values n over all the test cases in the input doesn't exceed 10^5.

Output

For each test case, output one integer — the smallest possible length of the segment which has at least one common point with all given segments.

Example

Input

4
3
4 5
5 9
7 7
5
11 19
4 17
16 16
3 12
14 17
1
1 10
1
1 1

Output

2
4
0
0

Note

In the first test case of the example, we can choose the segment [5;7] as the answer. It is the shortest segment that has at least one common point with all given segments.

```python
t = int(input())
for i in range(t):
    n = int(input())
    x = []
    y = []
    for i in range(n):
        a, b = map(int, input().split())
        x.append(a)
        y.append(b)
    if n == 1:
        print(0)
    elif min(y) > max(x):
        print(0)
    else:
        print(abs(max(x)-min(y)))

```


124_D. Squares

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

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

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

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

Input

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

Output

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

Examples

Input

2 2 1 0 0 1

Output

1

Input

2 2 10 11 0 1

Output

5

Input

2 4 3 -1 3 7

Output

2

Note

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

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

def cds(a, b, x, y):
    return (x + y) // (2 * a), (x - y) // (2 * b)

def norm(x, y):
    return max(x, y)

a, b, x1, y1, x2, y2 = map(int, input().split())
xp1, yp1 = cds(a, b, x1, y1)
xp2, yp2 = cds(a, b, x2, y2)
print(norm(abs(xp1 - xp2), abs(yp1 - yp2)))

```


1269_B. Modulo Equality

You are given a positive integer m and two integer sequence: a=[a_1, a_2, …, a_n] and b=[b_1, b_2, …, b_n]. Both of these sequence have a length n.

Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [0], [1,1], [2,3].

You need to find the non-negative integer x, and increase all elements of a_i by x, modulo m (i.e. you want to change a_i to (a_i + x) mod m), so it would be possible to rearrange elements of a to make it equal b, among them you need to find the smallest possible x.

In other words, you need to find the smallest non-negative integer x, for which it is possible to find some permutation p=[p_1, p_2, …, p_n], such that for all 1 ≤ i ≤ n, (a_i + x) mod m = b_{p_i}, where y mod m — remainder of division of y by m.

For example, if m=3, a = [0, 0, 2, 1], b = [2, 0, 1, 1], you can choose x=1, and a will be equal to [1, 1, 0, 2] and you can rearrange it to make it equal [2, 0, 1, 1], which is equal to b.

Input

The first line contains two integers n,m (1 ≤ n ≤ 2000, 1 ≤ m ≤ 10^9): number of elemens in arrays and m.

The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i < m).

The third line contains n integers b_1, b_2, …, b_n (0 ≤ b_i < m).

It is guaranteed that there exists some non-negative integer x, such that it would be possible to find some permutation p_1, p_2, …, p_n such that (a_i + x) mod m = b_{p_i}.

Output

Print one integer, the smallest non-negative integer x, such that it would be possible to find some permutation p_1, p_2, …, p_n such that (a_i + x) mod m = b_{p_i} for all 1 ≤ i ≤ n.

Examples

Input

4 3
0 0 2 1
2 0 1 1

Output

1

Input

3 2
0 0 0
1 1 1

Output

1

Input

5 10
0 0 0 1 2
2 1 0 0 0

Output

0

```python
import sys
input=sys.stdin.readline
from collections import deque
n,m=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a.sort()
b.sort()
a=deque(a)
b=deque(b)
ans=0
for _ in range(n):
	if a==b:
		break
	f=1
	for j in range(n-1):
		if b[j+1]-a[j+1]!=b[j]-a[j]:
			f=0
			break
	if f:
		if b[0]>a[0]:
			print(ans+b[0]-a[0])
			exit()
		else:
			print(ans+b[0]-a[0]+m)
			exit()
	p=m-a[-1]
	ans+=p
	ww=0
	for j in range(n):
		a[j]+=p
		if a[j]==m:
			ww=n-j
			break
	for j in range(ww):
		a.pop()
		a.appendleft(0)
print(ans)
```


1291_B. Array Sharpening

You're given an array a_1, …, a_n of n non-negative integers.

Let's call it sharpened if and only if there exists an integer 1 ≤ k ≤ n such that a_1 < a_2 < … < a_k and a_k > a_{k+1} > … > a_n. In particular, any strictly increasing or strictly decreasing array is sharpened. For example:

  * The arrays [4], [0, 1], [12, 10, 8] and [3, 11, 15, 9, 7, 4] are sharpened;
  * The arrays [2, 8, 2, 8, 6, 5], [0, 1, 1, 0] and [2, 5, 6, 9, 8, 8] are not sharpened.

You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any i (1 ≤ i ≤ n) such that a_i>0 and assign a_i := a_i - 1.

Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.

Input

The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 15\ 000) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5).

The second line of each test case contains a sequence of n non-negative integers a_1, …, a_n (0 ≤ a_i ≤ 10^9).

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

Output

For each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.

Example

Input

10
1
248618
3
12 10 8
6
100 11 15 9 7 8
4
0 1 1 0
2
0 0
2
0 1
2
1 0
2
1 1
3
0 1 0
3
1 0 1

Output

Yes
Yes
Yes
No
No
Yes
Yes
Yes
Yes
No

Note

In the first and the second test case of the first test, the given array is already sharpened.

In the third test case of the first test, we can transform the array into [3, 11, 15, 9, 7, 4] (decrease the first element 97 times and decrease the last element 4 times). It is sharpened because 3 < 11 < 15 and 15 > 9 > 7 > 4.

In the fourth test case of the first test, it's impossible to make the given array sharpened.

```python
t = int(input())

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

    rok = True
    rrok = True

    if n == 2 and a[0] == 0 and a[1] == 0:
        print("No")
    else:
        if n%2 == 0:
            ar = [0]*n

            for i in range(n//2):
                ar[i] = i
                ar[n-i-1] = i
            ar[n//2] = n//2

            for i in range(1, n-1):
                if a[i] < ar[i]:
                    rok = False

            ar = ar[::-1]

            for i in range(1, n-1):
                if a[i] < ar[i]:
                    rrok = False

            print("Yes" if (rok or rrok) else "No")

        else:
            for i in range(n):
                if a[i] < min(i, n-i-1):
                    rok = False
                    break

            print("Yes" if rok else "No")
```


1311_C. Perform the Combo

You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.

You know that you will spend m wrong tries to perform the combo and during the i-th try you will make a mistake right after p_i-th button (1 ≤ p_i < n) (i.e. you will press first p_i buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1-th try you press all buttons right and finally perform the combo.

I.e. if s="abca", m=2 and p = [1, 3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.

Your task is to calculate for each button (letter) the number of times you'll press it.

You have to answer t independent test cases.

Input

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

Then t test cases follow.

The first line of each test case contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of s and the number of tries correspondingly.

The second line of each test case contains the string s consisting of n lowercase Latin letters.

The third line of each test case contains m integers p_1, p_2, ..., p_m (1 ≤ p_i < n) — the number of characters pressed right during the i-th try.

It is guaranteed that the sum of n and the sum of m both does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5, ∑ m ≤ 2 ⋅ 10^5).

It is guaranteed that the answer for each letter does not exceed 2 ⋅ 10^9.

Output

For each test case, print the answer — 26 integers: the number of times you press the button 'a', the number of times you press the button 'b', ..., the number of times you press the button 'z'.

Example

Input

3
4 2
abca
1 3
10 5
codeforces
2 8 3 2 9
26 10
qwertyuioplkjhgfdsazxcvbnm
20 10 1 2 3 5 10 5 9 4

Output

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

Note

The first test case is described in the problem statement. Wrong tries are "a", "abc" and the final try is "abca". The number of times you press 'a' is 4, 'b' is 2 and 'c' is 2.

In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 9, 'd' is 4, 'e' is 5, 'f' is 3, 'o' is 9, 'r' is 3 and 's' is 1.

```python
from sys import stdin
from bisect import bisect_left
from collections import Counter
for k in range(int(stdin.readline())):
    n,m=[int(x) for x in stdin.readline().split()]
    s=input()
    d=Counter(s)
    l=list(map(int,stdin.readline().split()))
    l.sort()
    ans=[0 for j in range(0,26)]
    for j in range(0,len(s)):
        n=len(l)-bisect_left(l,j+1)
        ans[ord(s[j])-97]+=(n)
    e=list(d.keys())
    try:
        for i in range(0,len(e)):
            ans[ord(e[i])-97]+=(d[e[i]])
    except(Exception):
        pass
    print(*ans)
```


1334_A. Level Statistics

Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.

All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by 1. If he manages to finish the level successfully then the number of clears increases by 1 as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).

Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.

So he peeked at the stats n times and wrote down n pairs of integers — (p_1, c_1), (p_2, c_2), ..., (p_n, c_n), where p_i is the number of plays at the i-th moment of time and c_i is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).

Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.

Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.

Help him to check the correctness of his records.

For your convenience you have to answer multiple independent test cases.

Input

The first line contains a single integer T (1 ≤ T ≤ 500) — the number of test cases.

The first line of each test case contains a single integer n (1 ≤ n ≤ 100) — the number of moments of time Polycarp peeked at the stats.

Each of the next n lines contains two integers p_i and c_i (0 ≤ p_i, c_i ≤ 1000) — the number of plays and the number of clears of the level at the i-th moment of time.

Note that the stats are given in chronological order.

Output

For each test case print a single line.

If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES".

Otherwise, print "NO".

You can print each letter in any case (upper or lower).

Example

Input

6
3
0 0
1 1
1 2
2
1 0
1000 3
4
10 1
15 2
10 2
15 2
1
765 432
2
4 4
4 3
5
0 0
1 0
1 0
1 0
1 0

Output

NO
YES
NO
YES
NO
YES

Note

In the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.

The second test case is a nice example of a Super Expert level.

In the third test case the number of plays decreased, which is impossible.

The fourth test case is probably an auto level with a single jump over the spike.

In the fifth test case the number of clears decreased, which is also impossible.

Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.

```python
T=int(input())
list=[]
c=-1
d=-1
for i in range(T):
  n=int(input())
  k="Yes"
  for j in range(n):
    a,b=map(int,input().split())
    if a>=b and c<=a and d<=b and (b-d)<=(a-c):
        g=0
    else:
        k="No"
    c=a
    d=b
  c=-1
  d=-1
  list.append(k)
for i in range(len(list)):
  print(list[i])
```


1354_C2. Not So Simple Polygon Embedding

The statement of this problem is the same as the statement of problem C1. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.

You are given a regular polygon with 2 ⋅ n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.

Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.

You can rotate 2n-gon and/or the square.

Input

The first line contains a single integer T (1 ≤ T ≤ 200) — the number of test cases.

Next T lines contain descriptions of test cases — one per line. Each line contains single odd integer n (3 ≤ n ≤ 199). Don't forget you need to embed 2n-gon, not an n-gon.

Output

Print T real numbers — one per test case. For each test case, print the minimum length of a side of the square 2n-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed 10^{-6}.

Example

Input

3
3
5
199

Output

1.931851653
3.196226611
126.687663595

```python
# Why do we fall ? So we can learn to pick ourselves up.

from math import pi,cos
t = int(input())
for _ in range(0,t):
    n = int(input())
    theta = pi/4
    delta = pi/n
    maxi,mini,x = 0,0,0
    for i in range(0,2*n):
        x += cos(theta)
        theta -= delta
        maxi = max(maxi,x)
        mini = min(mini,x)
    print(maxi-mini)

"""

3
3
5
199

"""
```


1374_B. Multiply by 2, divide by 6

You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder).

Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that.

You have to answer t independent test cases.

Input

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

The only line of the test case contains one integer n (1 ≤ n ≤ 10^9).

Output

For each test case, print the answer — the minimum number of moves needed to obtain 1 from n if it's possible to do that or -1 if it's impossible to obtain 1 from n.

Example

Input

7
1
2
3
12
12345
15116544
387420489

Output

0
-1
2
-1
-1
12
36

Note

Consider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer 15116544:

  1. Divide by 6 and get 2519424;
  2. divide by 6 and get 419904;
  3. divide by 6 and get 69984;
  4. divide by 6 and get 11664;
  5. multiply by 2 and get 23328;
  6. divide by 6 and get 3888;
  7. divide by 6 and get 648;
  8. divide by 6 and get 108;
  9. multiply by 2 and get 216;
  10. divide by 6 and get 36;
  11. divide by 6 and get 6;
  12. divide by 6 and get 1.

```python
t=int(input())
for i in range(t):
    n=int(input())
    if n==1:
        print(0)
    else:
        if n%3!=0:
            print(-1)
        else:
            threes=0
            twos=0
            while n%3==0:
                threes+=1
                n=n//3
            while n%2==0:
                twos+=1
                n=n//2
            if n!=1 or twos>threes:
                print(-1)
            else:
                print(2*threes-twos)

```


1397_C. Multiples of Length

You are given an array a of n integers.

You want to make all elements of a equal to zero by doing the following operation exactly three times:

  * Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different).

It can be proven that it is always possible to make all elements of a equal to zero.

Input

The first line contains one integer n (1 ≤ n ≤ 100 000): the number of elements of the array.

The second line contains n elements of an array a separated by spaces: a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9).

Output

The output should contain six lines representing three operations.

For each operation, print two lines:

  * The first line contains two integers l, r (1 ≤ l ≤ r ≤ n): the bounds of the selected segment.

  * The second line contains r-l+1 integers b_l, b_{l+1}, ..., b_r (-10^{18} ≤ b_i ≤ 10^{18}): the numbers to add to a_l, a_{l+1}, …, a_r, respectively; b_i should be divisible by r - l + 1.

Example

Input

4
1 3 2 4

Output

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

```python
from sys import stdin

def inp():
    return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
    return int(stdin.buffer.readline())

def mpint():
    return map(int, stdin.buffer.readline().split())

# ############################## import
# ############################## main
# for __ in range(itg()):
n = itg()
if n == 1:
    print("1 1")
    print(-itg())
    print("1 1")
    print("0")
    print("1 1")
    print("0")
    exit()
arr = list(mpint())
print(1, n - 1)
print(*map(lambda x: x*(n-1), arr[:-1]))
print(2, n)
print(*[0] * (n - 2) + [arr[-1] * (n-1)])
print(1, n)
print(*map(lambda x: -x*n, arr))
# Please check!

```


1420_D. Rescue Nibel!

Ori and Sein have overcome many difficult challenges. They finally lit the Shrouded Lantern and found Gumon Seal, the key to the Forlorn Ruins. When they tried to open the door to the ruins... nothing happened.

Ori was very surprised, but Sein gave the explanation quickly: clever Gumon decided to make an additional defence for the door.

There are n lamps with Spirit Tree's light. Sein knows the time of turning on and off for the i-th lamp — l_i and r_i respectively. To open the door you have to choose k lamps in such a way that there will be a moment of time when they all will be turned on.

While Sein decides which of the k lamps to pick, Ori is interested: how many ways there are to pick such k lamps that the door will open? It may happen that Sein may be wrong and there are no such k lamps. The answer might be large, so print it modulo 998 244 353.

Input

First line contains two integers n and k (1 ≤ n ≤ 3 ⋅ 10^5, 1 ≤ k ≤ n) — total number of lamps and the number of lamps that must be turned on simultaneously.

Next n lines contain two integers l_i ans r_i (1 ≤ l_i ≤ r_i ≤ 10^9) — period of time when i-th lamp is turned on.

Output

Print one integer — the answer to the task modulo 998 244 353.

Examples

Input

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

Output

9

Input

3 1
1 1
2 2
3 3

Output

3

Input

3 2
1 1
2 2
3 3

Output

0

Input

3 3
1 3
2 3
3 3

Output

1

Input

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

Output

7

Note

In first test case there are nine sets of k lamps: (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 3, 6), (1, 4, 6), (2, 3, 6), (2, 4, 6), (2, 6, 7).

In second test case k=1, so the answer is 3.

In third test case there are no such pairs of lamps.

In forth test case all lamps are turned on in a time 3, so the answer is 1.

In fifth test case there are seven sets of k lamps: (1, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5), (4, 5).

```python
import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c for j in range(b)] for i in range(a)]
def list3d(a, b, c, d): return [[[d for k in range(c)] for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e for l in range(d)] for k in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10**19
MOD = 998244353
EPS = 10**-10

def compress(S):

    zipped, unzipped = {}, {}
    for i, a in enumerate(sorted(S)):
        zipped[a] = i
        unzipped[i] = a
    return zipped, unzipped

class ModTools:

    def __init__(self, MAX, MOD):

        MAX += 1
        self.MAX = MAX
        self.MOD = MOD
        factorial = [1] * MAX
        factorial[0] = factorial[1] = 1
        for i in range(2, MAX):
            factorial[i] = factorial[i-1] * i % MOD
        inverse = [1] * MAX
        inverse[MAX-1] = pow(factorial[MAX-1], MOD-2, MOD)
        for i in range(MAX-2, -1, -1):
            inverse[i] = inverse[i+1] * (i+1) % MOD
        self.fact = factorial
        self.inv = inverse

    def nCr(self, n, r):

        if n < r: return 0
        r = min(r, n-r)
        numerator = self.fact[n]
        denominator = self.inv[r] * self.inv[n-r] % self.MOD
        return numerator * denominator % self.MOD

N, K = MAP()
LR = []
S = set()
for i in range(N):
    l, r = MAP()
    r += 1
    LR.append((l, r))
    S.add(l)
    S.add(r)

zipped, _ = compress(S)
M = len(zipped)
lcnt = [0] * M
rcnt = [0] * M
for i in range(N):
    LR[i] = (zipped[LR[i][0]], zipped[LR[i][1]])
    lcnt[LR[i][0]] += 1
    rcnt[LR[i][1]] += 1

cur = 0
ans = 0
mt = ModTools(N, MOD)
for i in range(M):
    cur -= rcnt[i]
    while lcnt[i]:
        if cur >= K-1:
            ans += mt.nCr(cur, K-1)
            ans %= MOD
        cur += 1
        lcnt[i] -= 1
print(ans)

```


1466_C. Canine poetry

After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades.

Orpheus, a famous poet, and musician plans to calm Cerberus with his poetry and safely walk past him. He created a very peculiar poem for Cerberus. It consists only of lowercase English letters.

We call a poem's substring a palindrome if and only if it reads the same backwards and forwards. A string a is a substring of a string b if a can be obtained from b by deleting several (possibly zero or all) characters from the beginning and several (possibly zero or all) characters from the end.

Unfortunately, Cerberus dislikes palindromes of length greater than 1. For example in the poem abaa the hound of Hades wouldn't like substrings aba and aa.

Orpheus can only calm Cerberus if the hound likes his poetry. That's why he wants to change his poem so that it does not contain any palindrome substrings of length greater than 1.

Orpheus can modify the poem by replacing a letter at any position with any lowercase English letter. He can use this operation arbitrarily many times (possibly zero). Since there can be many palindromes in his poem, he may have to make some corrections. But how many, exactly? Given the poem, determine the minimal number of letters that have to be changed so that the poem does not contain any palindromes of length greater than 1.

Input

The first line of the input contains a single integer t (1 ≤ t ≤ 10^5) denoting the number of test cases, then t test cases follow.

The first and only line of each test case contains a non-empty string of lowercase English letters, Orpheus' poem.

The sum of the length of Orpheus' poems in all test cases will not exceed 10^5.

Output

You should output t lines, i-th line should contain a single integer, answer to the i-th test case.

Example

Input

7
babba
abaac
codeforces
zeroorez
abcdcba
bbbbbbb
a

Output

1
1
0
1
1
4
0

Note

In the first test case, we can replace the third character with c and obtain a palindrome-less poem bacba.

In the second test case, we can replace the third character with d and obtain a palindrome-less poem abdac.

In the third test case, the initial poem already doesn't contain any palindromes, so Orpheus doesn't need to change anything there.

```python
import math
t=int(input())
for i in range(t):
    s=input()
    s=list(s)
    l=len(s)
    if l==1:
        print(0)
    elif l==2:
        if s[0]==s[1]:
            print(1)
        else:
            print(0)
    else:
        j=0
        c=0
        while(j<l):
            if j==l-1:
                break
            elif j==l-2:
                if s[j]==s[j+1]:
                    c+=1
                break
            else:
                if s[j]==s[j+1] and s[j+1]==s[j+2]:
                    c+=2
                    j+=3
                elif s[j]==s[j+2]:
                    c+=1
                    s[j+2]=str(j)
                    j+=1
                elif s[j]==s[j+1]:
                    c+=1
                    j+=2
                else:
                    j+=1

        print(c)

```


1490_D. Permutation Transformation

A permutation — is a sequence of length n integers from 1 to n, in which all the numbers occur exactly once. For example, [1], [3, 5, 2, 1, 4], [1, 3, 2] — permutations, and [2, 3, 2], [4, 3, 1], [0] — no.

Polycarp was recently gifted a permutation a[1 ... n] of length n. Polycarp likes trees more than permutations, so he wants to transform permutation a into a rooted binary tree. He transforms an array of different integers into a tree as follows:

  * the maximum element of the array becomes the root of the tree;
  * all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;
  * all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child.

For example, if he builds a tree by permutation a=[3, 5, 2, 1, 4], then the root will be the element a_2=5, and the left subtree will be the tree that will be built for the subarray a[1 ... 1] = [3], and the right one — for the subarray a[3 ... 5] = [2, 1, 4]. As a result, the following tree will be built:

<image> The tree corresponding to the permutation a=[3, 5, 2, 1, 4].

Another example: let the permutation be a=[1, 3, 2, 7, 5, 6, 4]. In this case, the tree looks like this:

<image> The tree corresponding to the permutation a=[1, 3, 2, 7, 5, 6, 4].

Let us denote by d_v the depth of the vertex a_v, that is, the number of edges on the path from the root to the vertex numbered a_v. Note that the root depth is zero. Given the permutation a, for each vertex, find the value of d_v.

Input

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

The first line of each test case contains an integer n (1 ≤ n ≤ 100) — the length of the permutation.

This is followed by n numbers a_1, a_2, …, a_n — permutation a.

Output

For each test case, output n values — d_1, d_2, …, d_n.

Example

Input

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

Output

1 0 2 3 1
0
0 1 3 2

```python
import sys
input=sys.stdin.readline
I = lambda : list(map(int,input().split()))

t,=I()
for _ in range(t):
	n,=I()
	l=I()
	an=[0]*n
	for i in range(n):
		x=y=0
		j=i+1
		x=l[i]
		while j<n:
			if l[j]>x:
				an[i]+=1
				x=l[j]
			if l[j]==n:
				break
			j+=1
		j=i-1
		x=l[i]
		while j>-1:
			if l[j]>x:
				an[i]+=1
				x=l[j]
			if l[j]==n:
				break
			j-=1
	print(*an)
```