1463_C. Busy Robot

You have a robot that can move along a number line. At time moment 0 it stands at point 0.

You give n commands to the robot: at time t_i seconds you command the robot to go to point x_i. Whenever the robot receives a command, it starts moving towards the point x_i with the speed of 1 unit per second, and he stops when he reaches that point. However, while the robot is moving, it ignores all the other commands that you give him.

For example, suppose you give three commands to the robot: at time 1 move to point 5, at time 3 move to point 0 and at time 6 move to point 4. Then the robot stands at 0 until time 1, then starts moving towards 5, ignores the second command, reaches 5 at time 6 and immediately starts moving to 4 to execute the third command. At time 7 it reaches 4 and stops there.

You call the command i successful, if there is a time moment in the range [t_i, t_{i + 1}] (i. e. after you give this command and before you give another one, both bounds inclusive; we consider t_{n + 1} = +∞) when the robot is at point x_i. Count the number of successful commands. Note that it is possible that an ignored command is successful.

Input

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

The first line of a test case contains a single integer n (1 ≤ n ≤ 10^5) — the number of commands.

The next n lines describe the commands. The i-th of these lines contains two integers t_i and x_i (1 ≤ t_i ≤ 10^9, -10^9 ≤ x_i ≤ 10^9) — the time and the point of the i-th command.

The commands are ordered by time, that is, t_i < t_{i + 1} for all possible i.

The sum of n over test cases does not exceed 10^5.

Output

For each testcase output a single integer — the number of successful commands.

Example

Input

8
3
1 5
3 0
6 4
3
1 5
2 4
10 -5
5
2 -5
3 1
4 1
5 1
6 1
4
3 3
5 -3
9 2
12 0
8
1 1
2 -6
7 2
8 3
12 -9
14 2
18 -1
23 9
5
1 -4
4 -7
6 -1
7 -3
8 -7
2
1 2
2 -2
6
3 10
5 5
8 0
12 -4
14 -7
19 -5

Output

1
2
0
2
1
1
0
2

Note

The movements of the robot in the first test case are described in the problem statement. Only the last command is successful.

In the second test case the second command is successful: the robot passes through target point 4 at time 5. Also, the last command is eventually successful.

In the third test case no command is successful, and the robot stops at -5 at time moment 7.

Here are the 0-indexed sequences of the positions of the robot in each second for each testcase of the example. After the cut all the positions are equal to the last one:

  1. [0, 0, 1, 2, 3, 4, 5, 4, 4, ...]
  2. [0, 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -5, ...]
  3. [0, 0, 0, -1, -2, -3, -4, -5, -5, ...]
  4. [0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, ...]
  5. [0, 0, 1, 0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -7, -8, -9, -9, -9, -9, -8, -7, -6, -5, -4, -3, -2, -1, -1, ...]
  6. [0, 0, -1, -2, -3, -4, -4, -3, -2, -1, -1, ...]
  7. [0, 0, 1, 2, 2, ...]
  8. [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -7, ...]

```python
import sys
import bisect
input=sys.stdin.readline
t=int(input())
for you in range(t):
    n=int(input())
    l=[]
    for i in range(n):
        z=input().split()
        u=int(z[0])
        v=int(z[1])
        l.append((u,v))
    l.append((10**18,0))
    counter=0
    currtime=0
    currpos=0
    reqtime=0
    reqpos=0
    for i in range(n):
        if(reqtime<=l[i][0]):
            #print("yes")
            currtime=l[i][0]
            currpos=reqpos
            reqtime=currtime+abs(currpos-l[i][1])
            reqpos=l[i][1]
            if(abs(reqpos-currpos)+currtime<=l[i+1][0]):
                counter+=1
                #print("done")
        else:
            #print("no")
            if((reqpos-currpos)*(l[i][1]-currpos)<0):
                continue
            if(abs(reqpos-currpos)<abs(l[i][1]-currpos)):
                continue
            z=currtime+abs(l[i][1]-currpos)
            #print(z)
            if(z>=l[i][0] and z<=l[i+1][0]):
                counter+=1
                #print("done")
    print(counter)
```


148_C. Terse princess

«Next please», — the princess called and cast an estimating glance at the next groom.

The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous ones added together, she exclaims «Wow!» (no «Oh...» in this case). At the sight of the first groom the princess stays calm and says nothing.

The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw n grooms, said «Oh...» exactly a times and exclaimed «Wow!» exactly b times. Your task is to output a sequence of n integers t1, t2, ..., tn, where ti describes the fortune of i-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.

Input

The only line of input data contains three integer numbers n, a and b (1 ≤ n ≤ 100, 0 ≤ a, b ≤ 15, n > a + b), separated with single spaces.

Output

Output any sequence of integers t1, t2, ..., tn, where ti (1 ≤ ti ≤ 50000) is the fortune of i-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1.

Examples

Input

10 2 3

Output

5 1 3 6 16 35 46 4 200 99

Input

5 0 0

Output

10 10 6 6 5

Note

Let's have a closer look at the answer for the first sample test.

  * The princess said «Oh...» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.
  * The princess exclaimed «Wow!» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.

```python
n,ohh,wow= list(map(int , input().split()))
if(wow==0):
    if(n>=ohh+2):
        print(1,end=" ")
        print(1,end=" ")
        for i in range(1,ohh+1):
            print(i+1,end=" ")
        for i in range(n-ohh-2):
            print(ohh+1,end=" ")
    elif(ohh==0):
        for i in range(n):
            print(1,end=" ")
    else:
        print(-1)
else:
    ans=1
    print(ans,end=" ")
    for i in range(wow):
        ans*= 2
        print(ans,end=" ")
    for i in range(1,ohh+1):
        print(ans+i,end=" ")
    for i in range(n-ohh-wow-1):
        print(1,end=" ")
```


1512_A. Spy Detected!

You are given an array a consisting of n (n ≥ 3) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array [4, 11, 4, 4] all numbers except one are equal to 4).

Print the index of the element that does not equal others. The numbers in the array are numbered from one.

Input

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

The first line of each test case contains a single integer n (3 ≤ n ≤ 100) — the length of the array a.

The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 100).

It is guaranteed that all the numbers except one in the a array are the same.

Output

For each test case, output a single integer — the index of the element that is not equal to others.

Example

Input

4
4
11 13 11 11
5
1 4 4 4 4
10
3 3 3 3 10 3 3 3 3 3
3
20 20 10

Output

2
1
5
3

```python
t=int(input())
for i in range(t):
	n=int(input())
	arr=[int(x) for x in input().split()]
	my_list=[]
	my_list1=[]
	for j in range(len(arr)):
		c_count=arr.count(arr[j])
		my_list.append(arr[j])
		my_list1.append(c_count)
	mid= min(my_list1)
	req=(my_list1.index(mid))
	req1=my_list[req]
	for k in range(len(arr)):
		if arr[k]==req1:
			print(k+1)
			break
```


1539_E. Game with Cards

The Alice's computer is broken, so she can't play her favorite card game now. To help Alice, Bob wants to answer n her questions.

Initially, Bob holds one card with number 0 in the left hand and one in the right hand. In the i-th question, Alice asks Bob to replace a card in the left or right hand with a card with number k_i (Bob chooses which of two cards he changes, Bob must replace exactly one card).

After this action, Alice wants the numbers on the left and right cards to belong to given segments (segments for left and right cards can be different). Formally, let the number on the left card be x, and on the right card be y. Then after the i-th swap the following conditions must be satisfied: a_{l, i} ≤ x ≤ b_{l, i}, and a_{r, i} ≤ y ≤ b_{r,i}.

Please determine if Bob can answer all requests. If it is possible, find a way to do it.

Input

The first line contains two integers n and m (2 ≤ n ≤ 100 000, 2 ≤ m ≤ 10^9) — the number of questions and the maximum possible value on the card.

Then n queries are described. Every description contains 3 lines.

The first line of the description of the i-th query contains a single integer k_i (0 ≤ k_i ≤ m) — the number on a new card.

The second line of the description of the i-th query contains two integers a_{l, i} and b_{l, i} (0 ≤ a_{l, i} ≤ b_{l, i} ≤ m) — the minimum and maximum values of the card at the left hand after the replacement.

The third line of the description of the i-th query contains two integers a_{r, i} and b_{r,i} (0 ≤ a_{r, i} ≤ b_{r,i} ≤ m) — the minimum and maximum values of the card at the right hand after the replacement.

Output

At the first line, print "Yes", if Bob can answer all queries, and "No" otherwise.

If Bob can answer all n queries, then at the second line print n numbers: a way to satisfy all requirements. If in i-th query Bob needs to replace the card in the left hand, print 0, otherwise print 1. If there are multiple answers, print any.

Examples

Input

2 10
3
0 3
0 2
2
0 4
0 2

Output

Yes
0 1

Input

2 10
3
0 3
0 2
2
3 4
0 1

Output

No

Input

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

Output

Yes
1 0 0 1 0


166_B. Polygons

You've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.

Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.

Input

The first line contains the only integer n (3 ≤ n ≤ 105) — the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≤ 109) — coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.

The next line contains a single integer m (3 ≤ m ≤ 2·104) — the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≤ 109) — the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.

The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.

Output

Print on the only line the answer to the problem — if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).

Examples

Input

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

Output

YES

Input

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

Output

NO

Input

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

Output

NO

```python
def convex_hull(points):
    points = sorted(set(points))

    if len(points) <= 1:
        return points

    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    lower = []
    for p in points:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0:
            lower.pop()
        lower.append(p)

    upper = []
    for p in reversed(points):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0:
            upper.pop()
        upper.append(p)

    return lower[:-1] + upper[:-1]

def d():
    total = []

    n = int(input())
    a, b = [], []
    for i in range(n):
        x,y = map(int,input().split())
        total.append((x,y))
        a.append((x,y))

    m = int(input())

    for j in range(m):
        x,y = map(int,input().split())
        total.append((x,y))
        b.append((x,y))

    set_a = set()
    for i in a:
        set_a.add(i)
    for j in b:
        if(j in set_a):
            print("NO")
            return

    if(sorted(a)==sorted(convex_hull(total))):
        print("YES")
    else:
        print("NO")

d()

```


208_A. Dubstep

Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.

Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.

For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".

Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.

Input

The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters. It is guaranteed that before Vasya remixed the song, no word contained substring "WUB" in it; Vasya didn't change the word order. It is also guaranteed that initially the song had at least one word.

Output

Print the words of the initial song that Vasya used to make a dubsteb remix. Separate the words with a space.

Examples

Input

WUBWUBABCWUB

Output

ABC

Input

WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB

Output

WE ARE THE CHAMPIONS MY FRIEND

Note

In the first sample: "WUBWUBABCWUB" = "WUB" + "WUB" + "ABC" + "WUB". That means that the song originally consisted of a single word "ABC", and all words "WUB" were added by Vasya.

In the second sample Vasya added a single word "WUB" between all neighbouring words, in the beginning and in the end, except for words "ARE" and "THE" — between them Vasya added two "WUB".

```python
word = input()
word = str.replace(word,'WUB',' ')
list1 = word.split()
print(' '.join(list1))

```


233_D. Table

John Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points.

John Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by 1000000007 (109 + 7).

You should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other.

Input

A single line contains space-separated integers n, m, k (1 ≤ n ≤ 100; n ≤ m ≤ 1018; 0 ≤ k ≤ n2) — the number of rows of the table, the number of columns of the table and the number of points each square must contain.

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

Output

In a single line print a single integer — the remainder from dividing the described number of ways by 1000000007 (109 + 7).

Examples

Input

5 6 1

Output

45

Note

Let's consider the first test case:

<image> The gray area belongs to both 5 × 5 squares. So, if it has one point, then there shouldn't be points in any other place. If one of the white areas has a point, then the other one also must have a point. Thus, there are about 20 variants, where the point lies in the gray area and 25 variants, where each of the white areas contains a point. Overall there are 45 variants.

```python
n,m,k=map(int,input().split())
M=int(1e9+7)

N=n*n
iv=[0]*(N+1)
iv[1]=1
for i in range(2, N+1):
    iv[i]=M-M//i*iv[M%i]%M
f1=[1]*(N+1)
for i in range(1, N+1):
    f1[i]=f1[i-1]*i%M
f2=[1]*(N+1)
for i in range(1, N+1):
    f2[i]=f2[i-1]*iv[i]%M
left=m%n
#m/n+1, m/n
def powM(b, p):
    r=1
    while p>0:
        if p%2>0:
            r=r*b%M
        b=b*b%M
        p//=2
    return r
c=[[powM(f1[n]*f2[j]%M*f2[n-j]%M, m//n+i) for j in range(n+1)] for i in range(2)]
#print(c)
dp=[[0]*(k+1) for i in range(n+1)]
dp[0][0]=1
for i in range(n):
    for j in range(k+1):
        #prune
        if j>i*n or j<k-(n-i)*n:
            continue
        for l in range(min(n, k-j)+1):
            # i,j -> i+1,j+l
            dp[i+1][j+l]=(dp[i+1][j+l]+c[i<left][l]*dp[i][j])%M
print(dp[n][k])
```


259_C. Little Elephant and Bits

The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.

To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).

The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

Input

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.

Output

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

Examples

Input

101

Output

11

Input

110010

Output

11010

Note

In the first sample the best strategy is to delete the second digit. That results in number 112 = 310.

In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.

```python
s=list(input())
for i in range(len(s)):
  if s[i]=='0':
    break
del(s[i])
print("".join(s))

```


282_C. XOR and OR

The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.

A Bitlandish string is a string made only of characters "0" and "1".

BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.

The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.

So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.

You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.

Input

The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths.

It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.

Output

Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.

Examples

Input

11
10

Output

YES

Input

1
01

Output

NO

Input

000
101

Output

NO

```python
def helper(a,b):
    n=len(a)
    m=len(b)
    if n!=m:
        return 'NO'
    if a==b:
        return 'YES'
    if a=='0'*n or b=='0'*m:
        return'NO'
    return 'YES'
a=input()
b=input()
print(helper(a,b))

```


305_B. Continued Fractions

A continued fraction of height n is a fraction of form <image>. You are given two rational numbers, one is represented as <image> and the other one is represented as a finite fraction of height n. Check if they are equal.

Input

The first line contains two space-separated integers p, q (1 ≤ q ≤ p ≤ 1018) — the numerator and the denominator of the first fraction.

The second line contains integer n (1 ≤ n ≤ 90) — the height of the second fraction. The third line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1018) — the continued fraction.

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

Output

Print "YES" if these fractions are equal and "NO" otherwise.

Examples

Input

9 4
2
2 4

Output

YES

Input

9 4
3
2 3 1

Output

YES

Input

9 4
3
1 2 4

Output

NO

Note

In the first sample <image>.

In the second sample <image>.

In the third sample <image>.

```python
#import math

def gcd(a, b):
   if b == 0:
      return a
   else:
     return gcd(b, a % b)

p, q = map(int, input().split())
n = int(input())
data = list(map(int, input().split()))
a = 1
b = data[-1]
for i in range(2, n + 1):
  a = b * data[n - i] + a
  a, b = b, a

a, b = b, a
nod = gcd(p, q)
p = p // nod
q = q // nod

if p == a and q == b:
  print("YES")
else:
  print("NO")
```


353_A. Domino

Valera has got n domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.

To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.

Input

The first line contains integer n (1 ≤ n ≤ 100), denoting the number of dominoes Valera has. Next n lines contain two space-separated integers xi, yi (1 ≤ xi, yi ≤ 6). Number xi is initially written on the upper half of the i-th domino, yi is initially written on the lower half.

Output

Print a single number — the minimum required number of seconds. If Valera can't do the task in any time, print  - 1.

Examples

Input

2
4 2
6 4

Output

0

Input

1
2 3

Output

-1

Input

3
1 4
2 3
4 4

Output

1

Note

In the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.

In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.

In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 8.

```python
n=int(input())
(eo,sl,su)=(0,0,0)
for i in range(0,n):
    (a,b)=map(int,input().split(" "))
    sl=sl+b
    su=su+a
    if (a%2==0 and b%2==1)or(a%2==1 and b%2==0):
        eo=1
if sl%2==0 and su%2==0:
    print(0)
elif((sl%2==1 and su%2==1)):
    if eo:
        print(1)
    else:
        print(-1)
else:
    print(-1)

```


377_B. Preparing for the Contest

Soon there will be held the world's largest programming contest, but the testing system still has m bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has n students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the i-th student wants to get ci 'passes' in his subjects (regardless of the volume of his work).

Bugs, like students, are not the same: every bug is characterized by complexity aj, and every student has the level of his abilities bi. Student i can fix a bug j only if the level of his abilities is not less than the complexity of the bug: bi ≥ aj, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously.

The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than s passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.

Input

The first line contains three space-separated integers: n, m and s (1 ≤ n, m ≤ 105, 0 ≤ s ≤ 109) — the number of students, the number of bugs in the system and the maximum number of passes the university is ready to give the students.

The next line contains m space-separated integers a1, a2, ..., am (1 ≤ ai ≤ 109) — the bugs' complexities.

The next line contains n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109) — the levels of the students' abilities.

The next line contains n space-separated integers c1, c2, ..., cn (0 ≤ ci ≤ 109) — the numbers of the passes the students want to get for their help.

Output

If the university can't correct all bugs print "NO".

Otherwise, on the first line print "YES", and on the next line print m space-separated integers: the i-th of these numbers should equal the number of the student who corrects the i-th bug in the optimal answer. The bugs should be corrected as quickly as possible (you must spend the minimum number of days), and the total given passes mustn't exceed s. If there are multiple optimal answers, you can output any of them.

Examples

Input

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

Output

YES
2 3 2 3

Input

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

Output

YES
1 3 1 3

Input

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

Output

YES
3 3 2 3

Input

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

Output

NO

Note

Consider the first sample.

The third student (with level 3) must fix the 2nd and 4th bugs (complexities 3 and 2 correspondingly) and the second student (with level 1) must fix the 1st and 3rd bugs (their complexity also equals 1). Fixing each bug takes one day for each student, so it takes 2 days to fix all bugs (the students can work in parallel).

The second student wants 3 passes for his assistance, the third student wants 6 passes. It meets the university's capabilities as it is ready to give at most 9 passes.

```python
from sys import stdin
import heapq

n,m,s = [int(x) for x in stdin.readline().split()]

bugs = [int(x) for x in stdin.readline().split()]
bugs = sorted([(bugs[x],x) for x in range(m)])

order = [x[1] for x in bugs]
bugs = [x[0] for x in bugs]

students = [int(x) for x in stdin.readline().split()]
rate = [int(x) for x in stdin.readline().split()]

valid = False
for x in range(n):
  if students[x] >= bugs[-1] and rate[x] <= s:
    valid = True
if not valid:
  print('NO')
else:
  print('YES')
  #print(students)
  for i,x in enumerate(students):
    low = 0
    high = m-1
    while high >= low:
      mid = (high+low)//2
      if bugs[mid] > x:
        high = mid-1
      else:
        low = mid+1
    #print(x,high)
    students[i] = high

  students = sorted([(students[x]+1,rate[x], x+1) for x in range(n)],reverse=True)
  #print(students)
  l1 = 1
  high = m

  lastValid = []
  lastD = 100000

  while l1 <= high:
    mid = (l1+high)//2
    shift = (mid-(m%mid))%mid
    segs = m//mid
    if shift > 0:
      segs += 1
    ind = 0
    q = []

    total = 0

    group = []

    for x in range(segs,0,-1):
      while ind<n:
        if (students[ind][0]+shift)//mid >= x:
          heapq.heappush(q,(students[ind][1],students[ind][2]))
          ind += 1
        else:
          break
      if q:
        r,i = heapq.heappop(q)
        group.append((x,i))
        total += r
      else:
        break
    if len(group) == segs and total <= s:
      #print(mid,total)
      high = mid-1
      lastValid = group
      lastD = mid
    else:
      l1 = mid+1
  complete = [0 for x in range(m)]
  lastValid.sort()
  mid = lastD
  shift = (mid-(m%mid))%mid
  skill = 1
  for bruh,i in lastValid:
    end = skill*mid-shift
    start = max(0,end-mid)
    for x in range(start,end):
      complete[x] = i
    skill += 1
  c2 = [0 for x in range(m)]
  for i,x in enumerate(complete):
    c2[order[i]] = x
  print(' '.join([str(x) for x in c2]))

```


421_E. Cup Trick

The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.

The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.

But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:

  * each cup contains a mark — a number from 1 to n; all marks on the cups are distinct;
  * the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).

When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.

Input

The first line contains integers n and m (1 ≤ n, m ≤ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 ≤ xi, yi ≤ n) — the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.

Output

If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.

If there are multiple correct answers, you should print the lexicographically minimum one.

Examples

Input

2 1
2 1

Output

2 1

Input

3 2
1 2
1 1

Output

2 1 3

Input

3 3
1 3
2 3
1 3

Output

-1

```python
import io
import os

# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py

class UnsortedList:
    def __init__(self, iterable=[], _load=200):
        """Initialize sorted list instance."""
        values = sorted(iterable)
        self._len = _len = len(values)
        self._load = _load
        self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
        self._list_lens = [len(_list) for _list in _lists]
        # self._mins = [_list[0] for _list in _lists]
        self._fen_tree = []
        self._rebuild = True

    def _fen_build(self):
        """Build a fenwick tree instance."""
        self._fen_tree[:] = self._list_lens
        _fen_tree = self._fen_tree
        for i in range(len(_fen_tree)):
            if i | i + 1 < len(_fen_tree):
                _fen_tree[i | i + 1] += _fen_tree[i]
        self._rebuild = False

    def _fen_update(self, index, value):
        """Update `fen_tree[index] += value`."""
        if not self._rebuild:
            _fen_tree = self._fen_tree
            while index < len(_fen_tree):
                _fen_tree[index] += value
                index |= index + 1

    def _fen_query(self, end):
        """Return `sum(_fen_tree[:end])`."""
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        x = 0
        while end:
            x += _fen_tree[end - 1]
            end &= end - 1
        return x

    def _fen_findkth(self, k):
        """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
        _list_lens = self._list_lens
        if k < _list_lens[0]:
            return 0, k
        if k >= self._len - _list_lens[-1]:
            return len(_list_lens) - 1, k + _list_lens[-1] - self._len
        if self._rebuild:
            self._fen_build()

        _fen_tree = self._fen_tree
        idx = -1
        for d in reversed(range(len(_fen_tree).bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
                idx = right_idx
                k -= _fen_tree[idx]
        return idx + 1, k

    def _delete(self, pos, idx):
        """Delete value at the given `(pos, idx)`."""
        _lists = self._lists
        # _mins = self._mins
        _list_lens = self._list_lens

        self._len -= 1
        self._fen_update(pos, -1)
        del _lists[pos][idx]
        _list_lens[pos] -= 1

        if _list_lens[pos]:
            # _mins[pos] = _lists[pos][0]
            pass
        else:
            del _lists[pos]
            del _list_lens[pos]
            # del _mins[pos]
            self._rebuild = True

    def __len__(self):
        """Return the size of the sorted list."""
        return self._len

    def __getitem__(self, index):
        """Lookup value at `index` in sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        return self._lists[pos][idx]

    def __delitem__(self, index):
        """Remove value at `index` from sorted list."""
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._delete(pos, idx)

    def __setitem__(self, index, value):
        pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
        self._lists[pos][idx] = value

    def insert(self, index, value):
        _load = self._load
        _lists = self._lists
        _list_lens = self._list_lens

        if _lists:
            pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
            self._fen_update(pos, 1)
            _list = _lists[pos]
            _list.insert(idx, value)
            _list_lens[pos] += 1
            if _load + _load < len(_list):
                _lists.insert(pos + 1, _list[_load:])
                _list_lens.insert(pos + 1, len(_list) - _load)
                _list_lens[pos] = _load
                del _list[_load:]
                self._rebuild = True
        else:
            _lists.append([value])
            _list_lens.append(1)
            self._rebuild = True
        self._len += 1

    def __iter__(self):
        """Return an iterator over the sorted list."""
        return (value for _list in self._lists for value in _list)

    def __reversed__(self):
        """Return a reverse iterator over the sorted list."""
        return (value for _list in reversed(self._lists) for value in reversed(_list))

    def __repr__(self):
        """Return string representation of sorted list."""
        return "SortedList({0})".format(list(self))

def solve(N, M, queries):
    idToMark = [-1 for i in range(N)]
    cups = UnsortedList([i for i in range(N)])
    for mark, pos in queries:
        pos -= 1  # 0-indexed
        cupId = cups[pos]
        del cups[pos]
        cups.insert(0, cupId)

        if idToMark[cupId] == -1:
            idToMark[cupId] = mark
        elif idToMark[cupId] != mark:
            return b"-1"

    markToCounts = [0 for i in range(N + 1)]
    for cupId, mark in enumerate(idToMark):
        if mark != -1:
            markToCounts[mark] += 1
            if markToCounts[mark] > 1:
                return b"-1"

    j = 1
    ans = []
    for cupId, mark in enumerate(idToMark):
        if mark != -1:
            ans.append(mark)
        else:
            while markToCounts[j] > 0:
                j += 1
            ans.append(j)
            j += 1
    return b" ".join(str(x).encode("ascii") for x in ans)

if False:
    N, M = 10 ** 6, 10 ** 6
    queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
    ans = solve(N, M, queries)
    # print(ans)
    assert ans != b"-1"
    exit()

if __name__ == "__main__":
    input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

    N, M = [int(x) for x in input().split()]
    queries = ((int(x) for x in input().split()) for i in range(M))
    ans = solve(N, M, queries)

    os.write(1, ans)

```


448_C. Painting Fence

Bizon the Champion isn't just attentive, he also is very hardworking.

Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.

Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.

Input

The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Output

Print a single integer — the minimum number of strokes needed to paint the whole fence.

Examples

Input

5
2 2 1 2 1

Output

3

Input

2
2 2

Output

2

Input

1
5

Output

1

Note

In the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.

In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.

In the third sample there is only one plank that can be painted using a single vertical stroke.

```python
import sys
sys.setrecursionlimit(10000) # hago n-1 llamadas recursivas para largo n, por default el limit es 1000 creo

def cantidad_de_brochazos(izq,der,altura):
    """

    :param izq: limite izquierdo de la zona a pintar
    :param der: limite derecho de la zona a pintar
    :param altura: altura hasta la cual ya esta pintada la cerca hacia abajo
    :return: cantidad necesaria
    """
    if izq > der:
        return 0  # caso base

    solo_vertical = der - izq + 1  # siempre esta la opcion de solo hacer trazos verticales
    altura_minima = min(L[izq:der + 1]) #necesitamos saber cual es el bloque con la menor altura
    minimo = izq + L[izq:der + 1].index(altura_minima)

    dividir_y_conquistar = L[minimo] - altura + cantidad_de_brochazos(izq,minimo - 1, L[minimo]) + \
                           cantidad_de_brochazos(minimo + 1, der, L[minimo])

    return min(solo_vertical, dividir_y_conquistar)

if __name__ == '__main__':
    n = int(sys.stdin.readline())
    L = list(map(int, input().split()))
    sys.stdout.write(str(cantidad_de_brochazos(0,n-1,0)))

```


46_D. Parking Lot

Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.

Input

The first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.

Output

For every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.

Examples

Input

30 1 2
6
1 5
1 4
1 5
2 2
1 5
1 4

Output

0
6
11
17
23

Input

30 1 1
6
1 5
1 4
1 5
2 2
1 5
1 4

Output

0
6
11
17
6

Input

10 1 1
1
1 12

Output

-1

```python
l, b, f = map(int, input().split())
p = [[-b, -b, -192], [l + f, l + f, -38]]
n = int(input())
for i in range(1, n + 1):
    a, h = map(int, input().split())
    if a == 1:
        k = False
        for w in range(len(p) - 1):
            if p[w + 1][0] - p[w][1] >= b + f + h:
                p.insert(w + 1, [p[w][1] + b, p[w][1] + b + h, i])
                k = True
                print(p[w][1] + b)
                break
        if not k:
            print(-1)
    else:
        for t in range(len(p)):
            if p[t][2] == h:
                p.pop(t)
                break

```


492_E. Vanya and Field

Vanya decided to walk in the field of size n × n cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi, yi). Vanya moves towards vector (dx, dy). That means that if Vanya is now at the cell (x, y), then in a second he will be at cell <image>. The following condition is satisfied for the vector: <image>, where <image> is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited.

Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.

Input

The first line contains integers n, m, dx, dy(1 ≤ n ≤ 106, 1 ≤ m ≤ 105, 1 ≤ dx, dy ≤ n) — the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi, yi (0 ≤ xi, yi ≤ n - 1) — the coordinates of apples. One cell may contain multiple apple trees.

Output

Print two space-separated numbers — the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.

Examples

Input

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

Output

1 3

Input

2 3 1 1
0 0
0 1
1 1

Output

0 0

Note

In the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3)

In the second sample: (0, 0) - (1, 1) - (0, 0)

```python
n,m,dx,dy = map(int,input().split())
x=y=0
a=[0]*n
c=[0]*n
for i in range(1,n):
  x = (x+dx)%n
  y = (y+dy)%n
  a[x]=y
for i in range(m):
  x,y = map(int,input().split())
  index = (y-a[x]+n)%n;
  c[index] += 1
ans = 0
for i in range(n):
  if c[i] > c[ans]: ans = i
print(0, ans)
```


543_D. Road Improvement

The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.

All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.

Your task is — for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 2·105) — the number of cities in the country. Next line contains n - 1 positive integers p2, p3, p4, ..., pn (1 ≤ pi ≤ i - 1) — the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i.

Output

Print n integers a1, a2, ..., an, where ai is the sought number of ways to improve the quality of the roads modulo 1 000 000 007 (109 + 7), if the capital of the country is at city number i.

Examples

Input

3
1 1

Output

4 3 3

Input

5
1 2 3 4

Output

5 8 9 8 5

```python

class Graph:
    def __init__(self, n_vertices, edges, directed=True, weighted=False):
        self.n_vertices = n_vertices
        self.edges = edges
        self.directed = directed
        self.weighted = weighted

    @property
    def adj(self):
        try:
            return self._adj
        except AttributeError:
            adj = [[] for _ in range(self.n_vertices)]
            def d_w(e):
                adj[e[0]].append((e[1],e[2]))
            def ud_w(e):
                adj[e[0]].append((e[1],e[2]))
                adj[e[1]].append((e[0],e[2]))
            def d_uw(e):
                adj[e[0]].append(e[1])
            def ud_uw(e):
                adj[e[0]].append(e[1])
                adj[e[1]].append(e[0])
            helper = (ud_uw, d_uw, ud_w, d_w)[self.directed+self.weighted*2]
            for e in self.edges:
                helper(e)
            self._adj = adj
            return adj

class RootedTree(Graph):
    def __init__(self, n_vertices, edges, root_vertex):
        self.root = root_vertex
        super().__init__(n_vertices, edges, False, False)

    @property
    def parent(self):
        try:
            return self._parent
        except AttributeError:
            adj = self.adj
            parent = [None]*self.n_vertices
            parent[self.root] = -1
            stack = [self.root]
            for i in range(self.n_vertices):
                v = stack.pop()
                for u in adj[v]:
                    if parent[u] is None:
                        parent[u] = v
                        stack.append(u)
            self._parent = parent
            return parent

    @property
    def children(self):
        try:
            return self._children
        except AttributeError:
            children = [None]*self.n_vertices
            for v,(l,p) in enumerate(zip(self.adj,self.parent)):
                children[v] = [u for u in l if u != p]
            self._children = children
            return children

    @property
    def dfs_order(self):
        try:
            return self._dfs_order
        except AttributeError:
            order = [None]*self.n_vertices
            children = self.children
            stack = [self.root]
            for i in range(self.n_vertices):
                v = stack.pop()
                order[i] = v
                for u in children[v]:
                    stack.append(u)
            self._dfs_order = order
            return order

from functools import reduce
from itertools import accumulate,chain
def rerooting(rooted_tree, merge, identity, finalize):
    N = rooted_tree.n_vertices
    parent = rooted_tree.parent
    children = rooted_tree.children
    order = rooted_tree.dfs_order

    # from leaf to parent
    dp_down = [None]*N
    for v in reversed(order[1:]):
        dp_down[v] = finalize(reduce(merge,
            (dp_down[c] for c in children[v]),
            identity))

    # from parent to leaf
    dp_up = [None]*N
    dp_up[0] = identity
    for v in order:
        if len(children[v]) == 0:
            continue
        temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,)
        left = tuple(accumulate(temp,merge))
        right = tuple(accumulate(reversed(temp[2:]),merge))
        for u,l,r in zip(children[v],left,reversed(right)):
            dp_up[u] = finalize(merge(l,r))

    res = [None]*N
    for v,l in enumerate(children):
        res[v] = reduce(merge,
                    (dp_down[u] for u in children[v]),
                    identity)
        res[v] = finalize(merge(res[v], dp_up[v]))

    return res

def solve(T):
    MOD = 10**9 + 7
    def merge(x,y):
        return (x*y)%MOD
    def finalize(x):
        return x+1

    return [v-1 for v in rerooting(T,merge,1,finalize)]

if __name__ == '__main__':
    N = int(input())
    edges = [(i+1,p-1) for i,p in enumerate(map(int,input().split()))]
    T = RootedTree(N, edges, 0)
    print(*solve(T))

```


570_A. Elections

The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.

The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.

At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.

Determine who will win the elections.

Input

The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively.

Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i.

It is guaranteed that the total number of people in all the cities does not exceed 109.

Output

Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

Examples

Input

3 3
1 2 3
2 3 1
1 2 1

Output

2

Input

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

Output

1

Note

Note to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.

Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.

```python
N, M = [int(x) for x in input().split()]

results = [0] * N

for i in range(M):
    city_results = [int(x) for x in input().split()]
    city_max = max(city_results)
    city_max_idx = city_results.index(city_max)

    results[city_max_idx] += 1

max_result = max(results)
max_index = results.index(max_result)

print(max_index + 1)
```


591_D. Chip 'n Dale Rescue Rangers

A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.

We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).

Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed <image> meters per second.

Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after <image> seconds the new position of the dirigible will be <image>.

Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.

It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.

Input

The first line of the input contains four integers x1, y1, x2, y2 (|x1|, |y1|, |x2|, |y2| ≤ 10 000) — the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively.

The second line contains two integers <image> and t (0 < v, t ≤ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively.

Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that <image> and <image>.

Output

Print a single real value — the minimum time the rescuers need to get to point (x2, y2). You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.

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

Examples

Input

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

Output

3.729935587093555327

Input

0 0 0 1000
100 1000
-50 0
50 0

Output

11.547005383792516398


613_B. Skills

Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai — the current skill level. All skills have the same maximum level A.

Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values:

  * The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf.
  * The minimum skill level among all skills (min ai), multiplied by coefficient cm.

Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force.

Input

The first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≤ n ≤ 100 000, 1 ≤ A ≤ 109, 0 ≤ cf, cm ≤ 1000, 0 ≤ m ≤ 1015).

The second line contains exactly n integers ai (0 ≤ ai ≤ A), separated by spaces, — the current levels of skills.

Output

On the first line print the maximum value of the Force that the character can achieve using no more than m currency units.

On the second line print n integers a'i (ai ≤ a'i ≤ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces.

Examples

Input

3 5 10 1 5
1 3 1

Output

12
2 5 2

Input

3 5 10 1 339
1 3 1

Output

35
5 5 5

Note

In the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1.

In the second test one should increase all skills to maximum.

```python
n,A,cf,cm,mN = map(int,input().split())

a = list(map(int,input().split()))
aCOPY = []
for elem in a:
    aCOPY.append(elem)
a.sort()

aPartialSum = [0]

for elem in a:
    aPartialSum.append(aPartialSum[-1] + elem)

maxScore = 0
ansMAXIBound = 0
ansMAXI = 0
ansMIN = 0
for MAXI in range(n + 1):
    currentScore = cf * MAXI
    if MAXI >= 1:
        mN -= (A - a[-MAXI])
    if mN < 0:
        break
    if MAXI == n:
        maxScore = currentScore + A * cm
        ansMAXIBound = 0
        ansMAXI = 10 ** 10
        ansMIN = 0
    # Find the maximum of minimum
    l = a[0]
    r = A - 1

    while l < r:
        m = (l + r + 1) // 2
        lA = 0
        rA = n - MAXI - 1
        while lA < rA:
            mA = (lA + rA) // 2
            if a[mA] > m:
                rA = mA - 1
            if a[mA] < m:
                lA = mA + 1
            if a[mA] == m:
                lA = mA
                rA = mA
                break
        lA = min(lA,n - MAXI - 1)
        if a[lA] > m:
            lA -= 1
        expenditure = (lA + 1) * m - aPartialSum[lA + 1]
        if expenditure > mN:
            r = m - 1
        else:
            l = m
    currentScore += l * cm
    if currentScore > maxScore:
        maxScore = currentScore
        ansMAXIBound = a[-MAXI]
        ansMAXI = MAXI
        ansMIN = l

print(maxScore)
inclCount = 0
for i in range(n):
    if aCOPY[i] > ansMAXIBound and inclCount < ansMAXI:
        aCOPY[i] = A
        inclCount += 1
for i in range(n):
    if aCOPY[i] == ansMAXIBound and inclCount < ansMAXI:
        aCOPY[i] = A
        inclCount += 1
    if aCOPY[i] < ansMIN:
        aCOPY[i] = ansMIN
print(" ".join(map(str,aCOPY)))

```


633_B. A Trivial Problem

Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem?

Input

The only line of input contains an integer m (1 ≤ m ≤ 100 000) — the required number of trailing zeroes in factorial.

Output

First print k — the number of values of n such that the factorial of n ends with m zeroes. Then print these k integers in increasing order.

Examples

Input

1

Output

5
5 6 7 8 9

Input

5

Output

0

Note

The factorial of n is equal to the product of all integers from 1 to n inclusive, that is n! = 1·2·3·...·n.

In the first sample, 5! = 120, 6! = 720, 7! = 5040, 8! = 40320 and 9! = 362880.

```python
from math import log
n = int(input())

def fivetorization(n):
	cnt = 0
	while n%5==0:
		cnt+=1
		n//=5
	return cnt

res=0
for i in range(5, 500001, 5):
	res+=fivetorization(i)
	if res==n:
		print(5)
		print(*[j for j in range(i, i+5)])
		quit()
print(0)
```


730_A. Toda 2

A group of n friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the i-th friend is ri.

The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all n friends. So the friends are faced with the problem: how to make all their ratings equal.

One way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than n) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so ri = 0 doesn't change after losing.

The friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members).

The friends want to make their ratings equal but as high as possible.

Help the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.

Input

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

The second line contains n non-negative integers r1, r2, ..., rn (0 ≤ ri ≤ 100), where ri is the initial rating of the i-th friend.

Output

In the first line, print a single integer R — the final rating of each of the friends.

In the second line, print integer t — the number of matches the friends have to play. Each of the following t lines should contain n characters '0' or '1', where the j-th character of the i-th line is equal to:

  * '0', if friend j should not play in match i,
  * '1', if friend j should play in match i.

Each line should contain between two and five characters '1', inclusive.

The value t should not exceed 104, it is guaranteed that such solution exists.

Remember that you shouldn't minimize the value t, but you should maximize R. If there are multiple solutions, print any of them.

Examples

Input

5
4 5 1 7 4

Output

1
8
01010
00011
01010
10010
00011
11000
00011
11000

Input

2
1 2

Output

0
2
11
11

Input

3
1 1 1

Output

1
0


774_E. Big Number and Remainder

Stepan has a very big positive integer.

Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.

Stepan wants to know the minimum remainder of the division by the given number m among all good shifts. Your task is to determine the minimum remainder of the division by m.

Input

The first line contains the integer which Stepan has. The length of Stepan's integer is between 2 and 200 000 digits, inclusive. It is guaranteed that Stepan's integer does not contain leading zeros.

The second line contains the integer m (2 ≤ m ≤ 108) — the number by which Stepan divides good shifts of his integer.

Output

Print the minimum remainder which Stepan can get if he divides all good shifts of his integer by the given number m.

Examples

Input

521
3

Output

2

Input

1001
5

Output

0

Input

5678901234567890123456789
10000

Output

123

Note

In the first example all good shifts of the integer 521 (good shifts are equal to 521, 215 and 152) has same remainder 2 when dividing by 3.

In the second example there are only two good shifts: the Stepan's integer itself and the shift by one position to the right. The integer itself is 1001 and the remainder after dividing it by 5 equals 1. The shift by one position to the right equals to 1100 and the remainder after dividing it by 5 equals 0, which is the minimum possible remainder.

```python
s = input()
m = int(input())
mn = m
ttt = 0
t = 0
ttt = 1
for i in range(1,len(s)):
    ttt = (ttt * 10) % m
for i in range(0,len(s)):
    t = (t * 10 + ord(s[i]) - ord('0')) % m
for i in range(0,len(s)):
    if s[i] != '0':
        mn = min(mn,t)
    t = t - (((ord(s[i])- ord('0')) * ttt) % m)
    if t < 0:
        t = t + m
    t = (t * 10 + (ord(s[i])- ord('0'))) % m
print(mn)

```


819_E. Mister B and Flight to the Moon

In order to fly to the Moon Mister B just needs to solve the following problem.

There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.

We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?

Input

The only line contains single integer n (3 ≤ n ≤ 300).

Output

If there is no answer, print -1.

Otherwise, in the first line print k (1 ≤ k ≤ n2) — the number of cycles in your solution.

In each of the next k lines print description of one cycle in the following format: first print integer m (3 ≤ m ≤ 4) — the length of the cycle, then print m integers v1, v2, ..., vm (1 ≤ vi ≤ n) — the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.

Examples

Input

3

Output

2
3 1 2 3
3 1 2 3

Input

5

Output

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

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

from collections import defaultdict

DEBUG = False

def main():
    if DEBUG:
        test()

    n = int(input())

    paths = cycles(n)

    print(len(paths))
    for p in paths:
        print('%d %s' % (len(p), ' '.join([str(v) for v in p])))

def cycles(n):
    """Builds a set of cycles for a fully connected graph with n vertices."""
    if n % 2 == 0:
        return even(n)
    else:
        return odd(n)

def even(n):
    """Builds a set of cycles that a graph with even vertices."""
    assert n % 2 == 0

    # Base case for complete graph such that V = {1, 2, 3, 4}.
    cycles = [[1, 2, 3], [2, 3, 4], [3, 4, 1], [4, 1, 2]]

    for i in range(6, n + 1, 2):
        a, b = i, i - 1

        # Use edges (a, 1), (a, 0), (b, 1), (b, 0), (a, b) exactly twice each.
        cycles += [[a, 1, b], [a, 2, b], [a, 1, b, 2]]

        # Similar to odd(...) as we are left with 2n - 2 edges to use
        # connected to i - 4 of the vertices V' = {3 ... i - 2}. Notice that
        # |V'| is even so we can apply the same strategy as in odd(...).
        for k in range(3, i - 1, 2):
            c, d = k, k + 1
            cycles += [[a, c, b, d]] * 2

    return cycles

def odd(n):
    """Builds a set of cycles that a graph with odd vertices."""
    assert n % 2 == 1

    # Base case for complete graph such that V = {1, 2, 3}.
    cycles = [[1, 2, 3]] * 2

    for i in range(5, n + 1, 2):
        a, b = i, i - 1
        # Say the new vertices are {a, b}. Since the graph is fully connected
        # adding these 2 vertices results in 2n + 1 more edges. We use a length
        # 3 cycle a -> b -> 1 > a twice to use up 3 of these edges.
        cycles += [[a, b, 1]] * 2

        # At this point we are left with 2n + 1 - 3 = 2n - 2 edges to use
        # connected to i - 3 of the vertices V' = {2 ... i - 2}. Notice that
        # |V'| is even. To use these edges and cover vertices V' we take pairs
        # c, d in V' and create two of each path a -> c -> b -> d -> a.
        for k in range(2, i - 1, 2):
            c, d = k, k + 1
            cycles += [[a, c, b, d]] * 2

    return cycles

def test():
    """Checks the cycles(...) solver for a bunch of inputs."""
    print('Testing...')

    for n in range(3, 300, 21):
        check(n, cycles(n))

    print('Tests pass!')

def check(n, paths):
    """Checks the solution for errors."""
    # Check that all vertices are covered.
    vertices = set(sum(paths, list()))
    assert vertices == set(range(1, n + 1))

    # Check that each edge is used exactly twice.
    counts = defaultdict(int)

    for p in paths:
        assert len(p) == 3 or len(p) == 4
        assert len(set(p)) == len(p)

        for i in range(len(p)):
            key = tuple(sorted([p[i - 1], p[i]]))
            counts[key] += 1

    for i in range(1, n + 1):
        for j in range(i + 1, n + 1):
            assert counts[(i, j)] == 2

if __name__ == '__main__':
    main()

```


845_C. Two TVs

Polycarp is a great fan of television.

He wrote down all the TV programs he is interested in for today. His list contains n shows, i-th of them starts at moment li and ends at moment ri.

Polycarp owns two TVs. He can watch two different shows simultaneously with two TVs but he can only watch one show at any given moment on a single TV. If one show ends at the same moment some other show starts then you can't watch them on a single TV.

Polycarp wants to check out all n shows. Are two TVs enough to do so?

Input

The first line contains one integer n (1 ≤ n ≤ 2·105) — the number of shows.

Each of the next n lines contains two integers li and ri (0 ≤ li < ri ≤ 109) — starting and ending time of i-th show.

Output

If Polycarp is able to check out all the shows using only two TVs then print "YES" (without quotes). Otherwise, print "NO" (without quotes).

Examples

Input

3
1 2
2 3
4 5

Output

YES

Input

4
1 2
2 3
2 3
1 2

Output

NO

```python
num_shows = int(input())

showtimes = []
for i in range(num_shows):
    showtime = [int(i) for i in input().split(" ")]
    showtimes.append((showtime[0], showtime[1]))

showtimes = sorted(showtimes)

tv1 = -1
tv2 = -1

start_time = min(st[0] for st in showtimes)
end_time = max(st[1] for st in showtimes)

fail_signal = False

for st in showtimes:
    start_time = st[0]
    end_time = st[1]

    if (start_time <= tv1) and (start_time <= tv2):
        fail_signal = True
        break
    else:
        if start_time > tv1: tv1 = end_time
        else: tv2 = end_time

if fail_signal: print("NO")
else: print("YES")
```


936_B. Sleepy Game

Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced.

Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves.

Your task is to help Petya find out if he can win the game or at least draw a tie.

Input

The first line of input contain two integers n and m — the number of vertices and the number of edges in the graph (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105).

The next n lines contain the information about edges of the graph. i-th line (1 ≤ i ≤ n) contains nonnegative integer ci — number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j — indices of these vertices (1 ≤ ai, j ≤ n, ai, j ≠ i).

It is guaranteed that the total sum of ci equals to m.

The next line contains index of vertex s — the initial position of the chip (1 ≤ s ≤ n).

Output

If Petya can win print «Win» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≤ k ≤ 106) — the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game.

If Petya can't win but can draw a tie, print «Draw» in the only line. Otherwise print «Lose».

Examples

Input

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

Output

Win
1 2 4 5

Input

3 2
1 3
1 1
0
2

Output

Lose

Input

2 2
1 2
1 1
1

Output

Draw

Note

In the first example the graph is the following:

<image>

Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins.

In the second example the graph is the following:

<image>

Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses.

In the third example the graph is the following:

<image>

Petya can't win, but he can move along the cycle, so the players will draw a tie.

```python
import sys

data = sys.stdin.readlines()
n, m = map(int, data[0].split())
g = {}
for i, line in enumerate(data[1:-1], 1):
    g[i] = list(map(int, line.split()[1:]))
mk = {}
start = int(data[-1])
queue = [(start, 0, -1, 1)]
cycle = False
while len(queue) > 0:
    v, player, prev, color = queue.pop()
    if color == 2:
        mk[(v, player)] = (prev, 2)
        continue
    if mk.get((v, player), None):
        if mk[(v, player)][1] == 1:
            cycle = True
        continue
    mk[(v, player)] = (prev, 1)
    queue.append((v, player, prev, 2))
    for w in g[v]:
        queue.append((w, 1-player, v, 1))

sol = None
for v in range(1, n+1):
    if len(g[v]) == 0 and mk.get((v, 1), None):
        sol = v
        break
if sol:
    path = [sol]
    cur = (sol, 1)
    while cur != (start, 0):
        cur = (mk.get(cur)[0], 1-cur[1])
        path.append(cur[0])
    print('Win')
    print(*path[::-1])
elif cycle:
    print('Draw')
else:
    print('Lose')

```


961_G. Partitions

You are given a set of n elements indexed from 1 to n. The weight of i-th element is wi. The weight of some subset of a given set is denoted as <image>. The weight of some partition R of a given set into k subsets is <image> (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).

Calculate the sum of weights of all partitions of a given set into exactly k non-empty subsets, and print it modulo 109 + 7. Two partitions are considered different iff there exist two elements x and y such that they belong to the same set in one of the partitions, and to different sets in another partition.

Input

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 2·105) — the number of elements and the number of subsets in each partition, respectively.

The second line contains n integers wi (1 ≤ wi ≤ 109)— weights of elements of the set.

Output

Print one integer — the sum of weights of all partitions of a given set into k non-empty subsets, taken modulo 109 + 7.

Examples

Input

4 2
2 3 2 3

Output

160

Input

5 2
1 2 3 4 5

Output

645

Note

Possible partitions in the first sample:

  1. {{1, 2, 3}, {4}}, W(R) = 3·(w1 + w2 + w3) + 1·w4 = 24;
  2. {{1, 2, 4}, {3}}, W(R) = 26;
  3. {{1, 3, 4}, {2}}, W(R) = 24;
  4. {{1, 2}, {3, 4}}, W(R) = 2·(w1 + w2) + 2·(w3 + w4) = 20;
  5. {{1, 3}, {2, 4}}, W(R) = 20;
  6. {{1, 4}, {2, 3}}, W(R) = 20;
  7. {{1}, {2, 3, 4}}, W(R) = 26;

Possible partitions in the second sample:

  1. {{1, 2, 3, 4}, {5}}, W(R) = 45;
  2. {{1, 2, 3, 5}, {4}}, W(R) = 48;
  3. {{1, 2, 4, 5}, {3}}, W(R) = 51;
  4. {{1, 3, 4, 5}, {2}}, W(R) = 54;
  5. {{2, 3, 4, 5}, {1}}, W(R) = 57;
  6. {{1, 2, 3}, {4, 5}}, W(R) = 36;
  7. {{1, 2, 4}, {3, 5}}, W(R) = 37;
  8. {{1, 2, 5}, {3, 4}}, W(R) = 38;
  9. {{1, 3, 4}, {2, 5}}, W(R) = 38;
  10. {{1, 3, 5}, {2, 4}}, W(R) = 39;
  11. {{1, 4, 5}, {2, 3}}, W(R) = 40;
  12. {{2, 3, 4}, {1, 5}}, W(R) = 39;
  13. {{2, 3, 5}, {1, 4}}, W(R) = 40;
  14. {{2, 4, 5}, {1, 3}}, W(R) = 41;
  15. {{3, 4, 5}, {1, 2}}, W(R) = 42.

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

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

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

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

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

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

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

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

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

def xorfactorial(num):#排他的論理和の階乗
    if num==0:
        return 0
    elif num==1:
        return 1
    elif num==2:
        return 3
    elif num==3:
        return 0
    else:
        x=baseorder(num)
        return (2**x)*((num-2**x+1)%2)+function(num-2**x)

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

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

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

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

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

        self.group -= 1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class Matrix():
    mod=10**9+7

    def set_mod(m):
        Matrix.mod=m

    def __init__(self,L):
        self.row=len(L)
        self.column=len(L[0])
        self._matrix=L
        for i in range(self.row):
            for j in range(self.column):
                self._matrix[i][j]%=Matrix.mod

    def __getitem__(self,item):
        if type(item)==int:
            raise IndexError("you must specific row and column")
        elif len(item)!=2:
            raise IndexError("you must specific row and column")

        i,j=item
        return self._matrix[i][j]

    def __setitem__(self,item,val):
        if type(item)==int:
            raise IndexError("you must specific row and column")
        elif len(item)!=2:
            raise IndexError("you must specific row and column")

        i,j=item
        self._matrix[i][j]=val

    def __add__(self,other):
        if (self.row,self.column)!=(other.row,other.column):
            raise SizeError("sizes of matrixes are different")

        res=[[0 for j in range(self.column)] for i in range(self.row)]
        for i in range(self.row):
            for j in range(self.column):
                res[i][j]=self._matrix[i][j]+other._matrix[i][j]
                res[i][j]%=Matrix.mod
        return Matrix(res)

    def __sub__(self,other):
        if (self.row,self.column)!=(other.row,other.column):
            raise SizeError("sizes of matrixes are different")

        res=[[0 for j in range(self.column)] for i in range(self.row)]
        for i in range(self.row):
            for j in range(self.column):
                res[i][j]=self._matrix[i][j]-other._matrix[i][j]
                res[i][j]%=Matrix.mod
        return Matrix(res)

    def __mul__(self,other):
        if type(other)!=int:
            if self.column!=other.row:
                raise SizeError("sizes of matrixes are different")

            res=[[0 for j in range(other.column)] for i in range(self.row)]
            for i in range(self.row):
                for j in range(other.column):
                    temp=0
                    for k in range(self.column):
                        temp+=self._matrix[i][k]*other._matrix[k][j]
                    res[i][j]=temp%Matrix.mod
            return Matrix(res)
        else:
            n=other
            res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)]
            return Matrix(res)

    def __pow__(self,m):
        if self.column!=self.row:
            raise MatrixPowError("the size of row must be the same as that of column")

        n=self.row
        res=Matrix([[int(i==j) for i in range(n)] for j in range(n)])
        while m:
            if m%2==1:
                res=res*self
            self=self*self
            m//=2
        return res

    def __str__(self):
        res=[]
        for i in range(self.row):
            for j in range(self.column):
                res.append(str(self._matrix[i][j]))
                res.append(" ")
            res.append("\n")
        res=res[:len(res)-1]
        return "".join(res)

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

input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())

def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

mod = 10**9 + 7
N = 2*10**5
g1 = [1]*(N+1)
g2 = [1]*(N+1)
inverse = [1]*(N+1)

for i in range( 2, N + 1 ):
    g1[i]=( ( g1[i-1] * i ) % mod )
    inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2[i]=( (g2[i-1] * inverse[i]) % mod )
inverse[0]=0

N,K = mi()
w = li()

def solve(N,K,w):
    S = sum(w) % mod
    res = 0
    for i in range(K):
        t = 0
        if N>=1:
            t += pow(i+1,N-1,mod) * g2[N-1]
            t %= mod
        if N>=2:
            t += pow(i+1,N-2,mod) * g2[N-2]
            t %= mod
        if i%2:
            res -= t * cmb(K-1,i,mod)
        else:
            res += t * cmb(K-1,i,mod)
        res %= mod

    res *= g1[N-1] * g2[K-1] * S
    res %= mod

    if K%2==0:
        res = -res
        res %= mod

    return res

print(solve(N,K,w))

```


98_A. Help Victoria the Wise

Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.

The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)

Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem.

Input

The first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} — they are the colors of gems with which the box should be decorated.

Output

Print the required number of different ways to decorate the box.

Examples

Input

YYYYYY

Output

1

Input

BOOOOB

Output

2

Input

ROYGBV

Output

30

```python
from functools import reduce

def factorial(n):
    return reduce(lambda x, y: x*y, range(1,n+1))

colors = {
    'R' : 0,
    'O' : 0,
    'Y' : 0,
    'G' : 0,
    'B' : 0,
    'V' : 0
}

for c in list(input()):
    colors[c] += 1

amount = list(reversed(sorted([(colors[key], key) for key in colors])))

amount = [x[0] for x in amount]

if amount[0] == 6 or amount[0] == 5:
    print("1")
elif amount[0] == 4:
    print("2")
elif amount[0] == 3:
    if amount[1] == 3:
        print("2")
    elif amount[1] == 2:
        print("3")
    elif amount[1] == 1:
        print("5")
elif amount[0] == 2:
    if amount[1] == amount[2] == 2:
        print("6")
    elif amount[1] == 2:
        print("8")
    else:
        print(factorial(6) // 48)

elif amount[0] == 1:
    print(factorial(6) // 24)

```


p02604 M-SOLUTIONS Programming Contest 2020 - M's Solution

New AtCoder City has an infinite grid of streets, as follows:

* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.
* A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.
* There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.
M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.
M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

* 1 \leq N \leq 15
* -10 \ 000 \leq X_i \leq 10 \ 000
* -10 \ 000 \leq Y_i \leq 10 \ 000
* 1 \leq P_i \leq 1 \ 000 \ 000
* The locations of the N residential areas, (X_i, Y_i), are all distinct.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
:  :  :
X_N Y_N P_N

Output

Print the answer in N+1 lines.
The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Examples

Input

3
1 2 300
3 3 600
1 4 800

Output

2900
900
0
0

Input

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Output

13800
1600
0
0
0
0

Input

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Output

26700
13900
3200
1200
0
0
0

Input

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Output

2576709
1569381
868031
605676
366338
141903
0
0
0

```python
import sys
input = sys.stdin.readline
def main():
    n = int(input())
    l = [list(map(int,input().split())) for i in range(n)]

    xcal = [[0]*n for i in range(1<<n)]
    ycal = [[0]*n for i in range(1<<n)]

    for i in range(1<<n):
        for j in range(n):
            xcal[i][j] = abs(l[j][0])
            ycal[i][j] = abs(l[j][1])
            for k in range(n):
                if (i>>k) & 1:
                    xcal[i][j] = min(xcal[i][j],abs(l[j][0]-l[k][0]))
                    ycal[i][j] = min(ycal[i][j],abs(l[j][1]-l[k][1]))
            xcal[i][j] *= l[j][2]
            ycal[i][j] *= l[j][2]
    ans = [float("INF")]*(n+1)

    for i in range(1<<n):
        count = 0
        for j in range(n):
            if i >> j & 1:
                count += 1
        j = i
        while j >= 0:
            j &= i
            cost = 0
            for k in range(n):
                if not (i>>k & 1):
                    cost += min(xcal[j][k],ycal[i-j][k])
                if cost > ans[count]:
                    break
            ans[count] = min(ans[count],cost)
            j -= 1

    for i in ans:
        print(i)
if __name__ == "__main__":
    main()
```