1497_D. Genius

Please note the non-standard memory limit.

There are n problems numbered with integers from 1 to n. i-th problem has the complexity c_i = 2^i, tag tag_i and score s_i.

After solving the problem i it's allowed to solve problem j if and only if IQ < |c_i - c_j| and tag_i ≠ tag_j. After solving it your IQ changes and becomes IQ = |c_i - c_j| and you gain |s_i - s_j| points.

Any problem can be the first. You can solve problems in any order and as many times as you want.

Initially your IQ = 0. Find the maximum number of points that can be earned.

Input

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

The first line of each test case contains an integer n (1 ≤ n ≤ 5000) — the number of problems.

The second line of each test case contains n integers tag_1, tag_2, …, tag_n (1 ≤ tag_i ≤ n) — tags of the problems.

The third line of each test case contains n integers s_1, s_2, …, s_n (1 ≤ s_i ≤ 10^9) — scores of the problems.

It's guaranteed that sum of n over all test cases does not exceed 5000.

Output

For each test case print a single integer — the maximum number of points that can be earned.

Example

Input

5
4
1 2 3 4
5 10 15 20
4
1 2 1 2
5 10 15 20
4
2 2 4 1
2 8 19 1
2
1 1
6 9
1
1
666

Output

35
30
42
0
0

Note

In the first test case optimal sequence of solving problems is as follows:

  1. 1 → 2, after that total score is 5 and IQ = 2
  2. 2 → 3, after that total score is 10 and IQ = 4
  3. 3 → 1, after that total score is 20 and IQ = 6
  4. 1 → 4, after that total score is 35 and IQ = 14

In the second test case optimal sequence of solving problems is as follows:

  1. 1 → 2, after that total score is 5 and IQ = 2
  2. 2 → 3, after that total score is 10 and IQ = 4
  3. 3 → 4, after that total score is 15 and IQ = 8
  4. 4 → 1, after that total score is 35 and IQ = 14

In the third test case optimal sequence of solving problems is as follows:

  1. 1 → 3, after that total score is 17 and IQ = 6
  2. 3 → 4, after that total score is 35 and IQ = 8
  3. 4 → 2, after that total score is 42 and IQ = 12

```python
def nr():return int(input())
def nrs():return [int(i) for i in input().split()]
def f(n,t,s):
	d=[0]*n
	for i in range(1,n):
		for j in range(i-1,-1,-1):
			if t[i]==t[j]:continue
			sc=abs(s[i]-s[j])
			d[i],d[j]=max(d[i],d[j]+sc),max(d[j],d[i]+sc)
	return max(d)
for _ in range(nr()):
	n=nr()
	t=nrs()
	s=nrs()
	print(f(n,t,s))

```


151_C. Win or Freeze

You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself.

The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.

Input

The first line contains the only integer q (1 ≤ q ≤ 1013).

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

Output

In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.

Examples

Input

6

Output

2

Input

30

Output

1
6

Input

1

Output

1
0

Note

Number 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory.

```python
import sys
line = sys.stdin.readline()
N = int(line)
tmp = N
factor = []
i = 2
while i**2 <= tmp:
    if tmp % i == 0:
        tmp //= i
        factor.append(i)
    else: i += 1
if tmp != 1: factor.append(i)
if len(factor) == 2: print(2)
else:
    print(1)
    if len(factor) <= 1: print(0)
    else: print(factor[0] * factor[1])
```


1547_C. Pair Programming

Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.

It's known that they have worked together on the same file for n + m minutes. Every minute exactly one of them made one change to the file. Before they started, there were already k lines written in the file.

Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.

Monocarp worked in total for n minutes and performed the sequence of actions [a_1, a_2, ..., a_n]. If a_i = 0, then he adds a new line to the end of the file. If a_i > 0, then he changes the line with the number a_i. Monocarp performed actions strictly in this order: a_1, then a_2, ..., a_n.

Polycarp worked in total for m minutes and performed the sequence of actions [b_1, b_2, ..., b_m]. If b_j = 0, then he adds a new line to the end of the file. If b_j > 0, then he changes the line with the number b_j. Polycarp performed actions strictly in this order: b_1, then b_2, ..., b_m.

Restore their common sequence of actions of length n + m such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence [a_1, a_2, ..., a_n] and Polycarp's — subsequence [b_1, b_2, ..., b_m]. They can replace each other at the computer any number of times.

Let's look at an example. Suppose k = 3. Monocarp first changed the line with the number 2 and then added a new line (thus, n = 2, \: a = [2, 0]). Polycarp first added a new line and then changed the line with the number 5 (thus, m = 2, \: b = [0, 5]).

Since the initial length of the file was 3, in order for Polycarp to change line number 5 two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be [0, 2, 0, 5] and [2, 0, 0, 5]. Changes [0, 0, 5, 2] (wrong order of actions) and [0, 5, 2, 0] (line 5 cannot be edited yet) are not correct.

Input

The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow. Before each test case, there is an empty line.

Each test case contains three lines. The first line contains three integers k, n, m (0 ≤ k ≤ 100, 1 ≤ n, m ≤ 100) — the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively.

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

The third line contains m integers b_1, b_2, ..., b_m (0 ≤ b_j ≤ 300).

Output

For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length n + m or -1 if such sequence doesn't exist.

Example

Input

5

3 2 2
2 0
0 5

4 3 2
2 0 5
0 6

0 2 2
1 0
2 3

5 4 4
6 0 8 0
0 7 0 9

5 4 1
8 7 8 0
0

Output

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

```python
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 10 23:15:34 2021

@author: Kevin Chang

Project: Codeforces Problem 1547C

"""

t = int(input())

for i in range(t):
    shit = input()
    k, n, m = list(map(int, input().split()))
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    res = []
    ress = 1

    for aa in a:
        if ress == -1:
            break
        elif aa == 0:
            k += 1
            res.append(aa)
        elif aa > k:
            while k < aa:
                if len(b) == 0:
                    ress = -1
                    break
                elif b[0] == 0:
                    k += 1
                    res.append(b.pop(0))
                elif b[0] > k:
                    ress = -1
                    break
                else:
                    res.append(b.pop(0))
            res.append(aa)
        else:
            res.append(aa)
            continue

    if ress == -1:
        print(ress)
    else:
        for bb in b:
            if ress == -1:
                break
            elif bb == 0:
                k += 1
                res.append(bb)
            elif bb > k:
                ress = -1
            else:
                res.append(bb)
            continue
        if ress == -1:
            print(ress)
        else:
            print(*res)

```


195_A. Let's Watch Football

Valeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the size of downloaded data per second.

The guys want to watch the whole video without any pauses, so they have to wait some integer number of seconds for a part of the video to download. After this number of seconds passes, they can start watching. Waiting for the whole video to download isn't necessary as the video can download after the guys started to watch.

Let's suppose that video's length is c seconds and Valeric and Valerko wait t seconds before the watching. Then for any moment of time t0, t ≤ t0 ≤ c + t, the following condition must fulfill: the size of data received in t0 seconds is not less than the size of data needed to watch t0 - t seconds of the video.

Of course, the guys want to wait as little as possible, so your task is to find the minimum integer number of seconds to wait before turning the video on. The guys must watch the video without pauses.

Input

The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 1000, a > b). The first number (a) denotes the size of data needed to watch one second of the video. The second number (b) denotes the size of data Valeric and Valerko can download from the Net per second. The third number (c) denotes the video's length in seconds.

Output

Print a single number — the minimum integer number of seconds that Valeric and Valerko must wait to watch football without pauses.

Examples

Input

4 1 1

Output

3

Input

10 3 2

Output

5

Input

13 12 1

Output

1

Note

In the first sample video's length is 1 second and it is necessary 4 units of data for watching 1 second of video, so guys should download 4 · 1 = 4 units of data to watch the whole video. The most optimal way is to wait 3 seconds till 3 units of data will be downloaded and then start watching. While guys will be watching video 1 second, one unit of data will be downloaded and Valerik and Valerko will have 4 units of data by the end of watching. Also every moment till the end of video guys will have more data then necessary for watching.

In the second sample guys need 2 · 10 = 20 units of data, so they have to wait 5 seconds and after that they will have 20 units before the second second ends. However, if guys wait 4 seconds, they will be able to watch first second of video without pauses, but they will download 18 units of data by the end of second second and it is less then necessary.

```python
from math import ceil
a,b,c = map(int,input().split())
t = (a*c - c*b)/b
print(ceil(t))
```


219_A. k-String

A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.

You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.

Input

The first input line contains integer k (1 ≤ k ≤ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000, where |s| is the length of string s.

Output

Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them.

If the solution doesn't exist, print "-1" (without quotes).

Examples

Input

2
aazz

Output

azaz

Input

3
abcabcabz

Output

-1

```python
from collections import Counter
import string
import math
import sys
def array_int():
    return [int(i) for i in sys.stdin.readline().split()]
def vary(number_of_variables):
    if number_of_variables==1:
        return int(sys.stdin.readline())
    if number_of_variables>=2:
        return map(int,sys.stdin.readline().split())
def makedict(var):
    return dict(Counter(var))
mod=100000007
k=vary(1)
s=input()
tt=makedict(list(s))
ans=''
for i in tt:
    if tt[i]%k!=0:
        print(-1)
        exit()
    else:
        ans+=i*(tt[i]//k)
print(ans*k)

```


242_C. King's Path

The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).

You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.

Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.

Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

Input

The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king.

The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.

It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.

Output

If there is no path between the initial and final position along allowed cells, print -1.

Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.

Examples

Input

5 7 6 11
3
5 3 8
6 7 11
5 2 5

Output

4

Input

3 4 3 10
3
3 1 4
4 5 9
3 10 10

Output

6

Input

1 1 2 10
2
1 1 3
2 6 10

Output

-1

```python
from collections import deque

x0,y0,x1,y1=list(map(int, input().split()))
n=int(input())
allowed={}
for i in range(n):
    r,a,b=list(map(int,input().split()))
    for j in range(a,b+1):
        allowed[(r,j)]=True
visited={}
q=deque()
q.append((x0,y0))
visited[(x0,y0)]=0
dire=[(-1,0),(1,0),(0,-1),(0,1),(-1,-1),(-1,1),(1,1),(1,-1)]
result=-1;
while len(q)>0:
    x,y=q.popleft()
    original_dist=visited[(x,y)]
    if x==x1 and y==y1:
        result=original_dist;
        break;
    for i in range(len(dire)):
        dx,dy=dire[i]
        nx,ny=x+dx,y+dy
        if (nx,ny) in allowed and (nx,ny) not in visited:
            q.append((nx,ny))
            visited[(nx,ny)]=original_dist+1
print(result)

```


268_A. Games

Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.

There are n teams taking part in the national championship. The championship consists of n·(n - 1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.

You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.

Input

The first line contains an integer n (2 ≤ n ≤ 30). Each of the following n lines contains a pair of distinct space-separated integers hi, ai (1 ≤ hi, ai ≤ 100) — the colors of the i-th team's home and guest uniforms, respectively.

Output

In a single line print the number of games where the host team is going to play in the guest uniform.

Examples

Input

3
1 2
2 4
3 4

Output

1

Input

4
100 42
42 100
5 42
100 5

Output

5

Input

2
1 2
1 2

Output

0

Note

In the first test case the championship consists of 6 games. The only game with the event in question is the game between teams 2 and 1 on the stadium of team 2.

In the second test sample the host team will have to wear guest uniform in the games between teams: 1 and 2, 2 and 1, 2 and 3, 3 and 4, 4 and 2 (the host team is written first).

```python
n=int(input())
mat=[]
for i in range(n):
    mat.append(list(map(int, input().rstrip().split())))
b=0
for i in range (n):
    for j in range (n):
        if mat[i][0]==mat[j][1]:
            b=b+1
print(b)
```


290_D. Orange

<image>

Input

The first line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be a letter of English alphabet, lowercase or uppercase.

The second line of the input is an integer between 0 and 26, inclusive.

Output

Output the required string.

Examples

Input

AprilFool
14

Output

AprILFooL

```python
text = input().lower()
caps = int(input())+97
for letter in text:
	print(letter.upper(), end='')if letter < chr(caps) else print(letter, end='')
print()
```


316_B2. EKG

In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.

(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.

The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.

Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...

As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.

Input

The first line contains two integers n (1 ≤ n ≤ 103) and x (1 ≤ x ≤ n) — the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.

The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.

The input limits for scoring 30 points are (subproblem B1):

  * It is guaranteed that the number of zero elements ai doesn't exceed 20.

The input limits for scoring 100 points are (subproblems B1+B2):

  * The number of zero elements ai is arbitrary.

Output

Print all possible positions of the Smart Beaver in the line in the increasing order.

Examples

Input

6 1
2 0 4 0 6 0

Output

2
4
6

Input

6 2
2 3 0 5 6 0

Output

2
5

Input

4 1
0 0 0 0

Output

1
2
3
4

Input

6 2
0 0 1 0 4 5

Output

1
3
4
6

Note

<image> Picture for the fourth test.

```python
def f(x, p):
    q = []
    while x:
        q.append(x)
        x = p[x]
    return q
from collections import defaultdict
n, k = map(int, input().split())
t = list(map(int, input().split()))
p = [0] * (n + 1)
for i, j in enumerate(t, 1):
    p[j] = i
p = [f(i, p) for i, j in enumerate(t, 1) if j == 0]
s = defaultdict(int)
for i in p:
    if k in i: t = {i.index(k) + 1}
    else: s[len(i)] += 1
s = [list(range(i, k * i + 1, i)) for i, k in s.items()]
for q in s:
    t |= {x + y for x in q for y in t}
print('\n'.join(map(str, sorted(list(t)))))
```


339_A. Helpful Maths

Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.

The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.

You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.

Input

The first line contains a non-empty string s — the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.

Output

Print the new sum that Xenia can count.

Examples

Input

3+2+1

Output

1+2+3

Input

1+1+3+1+3

Output

1+1+1+3+3

Input

2

Output

2

```python
x=input()
x=x.replace("+","")
x=sorted(x)
for i in range(1,2*len(x)-1,2):
    x.insert(i,"+")
x=''.join(x)
print(x)

```


361_C. Levko and Array Recovery

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

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

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

Input

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

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

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

Output

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

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

Examples

Input

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

Output

YES
4 7 4 7

Input

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

Output

NO

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

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

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

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

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

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

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

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

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

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


385_A. Bear and Raspberry

The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 ≤ i ≤ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.

Unfortunately, the bear has neither a honey barrel, nor the raspberry. At the same time, the bear's got a friend who is ready to lend him a barrel of honey for exactly one day for c kilograms of raspberry. That's why the bear came up with a smart plan. He wants to choose some day d (1 ≤ d < n), lent a barrel of honey and immediately (on day d) sell it according to a daily exchange rate. The next day (d + 1) the bear wants to buy a new barrel of honey according to a daily exchange rate (as he's got some raspberry left from selling the previous barrel) and immediately (on day d + 1) give his friend the borrowed barrel of honey as well as c kilograms of raspberry for renting the barrel.

The bear wants to execute his plan at most once and then hibernate. What maximum number of kilograms of raspberry can he earn? Note that if at some point of the plan the bear runs out of the raspberry, then he won't execute such a plan.

Input

The first line contains two space-separated integers, n and c (2 ≤ n ≤ 100, 0 ≤ c ≤ 100), — the number of days and the number of kilos of raspberry that the bear should give for borrowing the barrel.

The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi ≤ 100), the price of a honey barrel on day i.

Output

Print a single integer — the answer to the problem.

Examples

Input

5 1
5 10 7 3 20

Output

3

Input

6 2
100 1 10 40 10 40

Output

97

Input

3 0
1 2 3

Output

0

Note

In the first sample the bear will lend a honey barrel at day 3 and then sell it for 7. Then the bear will buy a barrel for 3 and return it to the friend. So, the profit is (7 - 3 - 1) = 3.

In the second sample bear will lend a honey barrel at day 1 and then sell it for 100. Then the bear buy the barrel for 1 at the day 2. So, the profit is (100 - 1 - 2) = 97.

```python

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

ans = 0
for i in range(n - 1):
	d = l[i] - l[i + 1] - c
	ans = max(ans, d)

print(ans)
```


405_E. Graph Cutting

Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest.

Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair.

For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph.

<image>

You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!

Input

The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected.

Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Output

If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them.

If it is impossible to cut the given graph, print "No solution" (without quotes).

Examples

Input

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

Output

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

Input

3 3
1 2
2 3
3 1

Output

No solution

Input

3 2
1 2
2 3

Output

1 2 3

```python
import sys

input = sys.stdin.readline
print = sys.stdout.write

def get_input():
    n, m = [int(x) for x in input().split(' ')]

    graph = [[] for _ in range(n + 1)]
    for _ in range(m):
        c1, c2 = [int(x) for x in input().split(' ')]
        graph[c1].append(c2)
        graph[c2].append(c1)

    if m % 2 != 0:
        print("No solution")
        exit(0)

    return graph

def partitions_bottom_up(graph):
    n = len(graph)
    w = [0] * n
    pi = [None] * n
    visited = [False] * n
    finished = [False] * n
    adjacency = [[] for _ in range(n)]

    stack = [1]
    while stack:
        current_node = stack[-1]

        if visited[current_node]:
            stack.pop()
            if finished[current_node]:
                w[current_node] = 0
                continue

            finished[current_node] = True
            unpair = []
            for adj in adjacency[current_node]:
                if w[adj] == 0:
                    unpair.append(adj)
                else:
                    print(' '.join([str(current_node), str(adj), str(w[adj]), '\n']))

            while len(unpair) > 1:
                print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n']))
            w[current_node] = unpair.pop() if unpair else 0
            continue

        visited[current_node] = True
        not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]]
        stack += not_blocked_neighbors
        adjacency[current_node] = not_blocked_neighbors

def partitions_top_down(graph):
    n = len(graph)
    visited = [False] * n

    for node in range(1, n):
        if not visited[node]:
            prev_node = None
            current_node = node
            while current_node is not None:
                visited[current_node] = True

                leafs = [prev_node] if prev_node is not None else []
                adjacency = []
                for adj in graph[current_node]:
                    if not visited[adj]:
                        if len(graph[adj]) == 1:
                            leafs.append(adj)
                        else:
                            adjacency.append(adj)

                while len(leafs) > 1:
                    print(' '.join([str(leafs.pop()), str(current_node), str(leafs.pop()), '\n']))

                if leafs:
                    adjacency.append(leafs.pop())

                while len(adjacency) > 1:
                    print(' '.join([str(adjacency.pop()), str(current_node), str(adjacency.pop()), '\n']))

                if adjacency:
                    current_node, prev_node = adjacency.pop(), current_node
                else:
                    current_node = None

if __name__ == "__main__":
    graph = get_input()
    partitions_bottom_up(graph)

```


433_A. Kitahara Haruki's Gift

Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.

Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.

But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?

Input

The first line contains an integer n (1 ≤ n ≤ 100) — the number of apples. The second line contains n integers w1, w2, ..., wn (wi = 100 or wi = 200), where wi is the weight of the i-th apple.

Output

In a single line print "YES" (without the quotes) if it is possible to divide all the apples between his friends. Otherwise print "NO" (without the quotes).

Examples

Input

3
100 200 100

Output

YES

Input

4
100 100 100 200

Output

NO

Note

In the first test sample Kitahara Haruki can give the first and the last apple to Ogiso Setsuna and the middle apple to Touma Kazusa.

```python
n = int(input())
a = list(input().split(' '))
a = list(int(x) for x in a)
one, two = 0, 0
for i in range(n):
    if a[i] == 100:
        one += 1
    else:
        two += 1
flag = False
if one%2 == 0 and two%2 == 0 or one > two and two % 2 == 1 and one % 2 == 0 and one >= 2 \
   or one < two and two%2 == 1 and one%2 == 0 and one >= 2:
    flag = True
if not flag:
    print('NO')
else:
    print('YES')

```


478_A. Initial Bet

There are five people playing a game called "Generosity". Each person gives some non-zero number of coins b as an initial bet. After all players make their bets of b coins, the following operation is repeated for several times: a coin is passed from one player to some other player.

Your task is to write a program that can, given the number of coins each player has at the end of the game, determine the size b of the initial bet or find out that such outcome of the game cannot be obtained for any positive number of coins b in the initial bet.

Input

The input consists of a single line containing five integers c1, c2, c3, c4 and c5 — the number of coins that the first, second, third, fourth and fifth players respectively have at the end of the game (0 ≤ c1, c2, c3, c4, c5 ≤ 100).

Output

Print the only line containing a single positive integer b — the number of coins in the initial bet of each player. If there is no such value of b, then print the only value "-1" (quotes for clarity).

Examples

Input

2 5 4 0 4

Output

3

Input

4 5 9 2 1

Output

-1

Note

In the first sample the following sequence of operations is possible:

  1. One coin is passed from the fourth player to the second player;
  2. One coin is passed from the fourth player to the fifth player;
  3. One coin is passed from the first player to the third player;
  4. One coin is passed from the fourth player to the second player.

```python
l=list(map(int,input().split()))
x=sum(l)
if(x%5==0 and x!=0):
    print(int(x/5))
else:
    print(-1)

```


500_C. New Year Book Reading

New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.

As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.

  1. He lifts all the books above book x.
  2. He pushes book x out of the stack.
  3. He puts down the lifted books without changing their order.
  4. After reading book x, he puts book x on the top of the stack.

<image>

He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.

After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

Input

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books.

The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book.

The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.

Output

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.

Examples

Input

3 5
1 2 3
1 3 2 3 1

Output

12

Note

Here's a picture depicting the example. Each vertical column presents the stacked books.

<image>

```python
n,m=map(int,input().split())
weight=[int(i) for i in input().split()]
order=[int(i) for i in input().split()]
stack=[]
for i in order:
    if i-1 not in stack:
        stack.append(i-1)
#print(stack)
ans=0
for i in order:
    #i=i-1
    currlift=sum(weight[i] for i in stack[0:stack.index(i-1)])
    ans+=currlift
    temp=i-1
    stack.remove(i-1)
    stack.insert(0,temp)
    #print(currlift)
    #print(stack)
print(ans)

```


526_A. King of Thieves

In this problem you will meet the simplified model of game King of Thieves.

In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.

<image>

An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.

A dungeon consists of n segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'.

One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number i1, he can make a sequence of jumps through the platforms i1 < i2 < ... < ik, if i2 - i1 = i3 - i2 = ... = ik - ik - 1. Of course, all segments i1, i2, ... ik should be exactly the platforms, not pits.

Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence i1, i2, ..., i5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.

Input

The first line contains integer n (1 ≤ n ≤ 100) — the number of segments on the level.

Next line contains the scheme of the level represented as a string of n characters '*' and '.'.

Output

If the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes).

Examples

Input

16
.**.*..*.***.**.

Output

yes

Input

11
.*.*...*.*.

Output

no

Note

In the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14.

```python
#!/usr/bin/env python
# jump.py - Codeforces <!!! NNNA !!!> quiz
#
# Copyright (C) 2015 Sergey
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#       http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Let's call a level to be good if you can perform a sequence of four jumps of
the same length or in the other words there must be a sequence consisting of
five platforms so that the intervals between consecutive platforms are of the
same length. Given the scheme of the level, check if it is good.

Input

The first line contains integer n (1<=n<=100) - the number of segments on
the level.  Next line contains the scheme of the level represented as a string
of n characters '*' and '.'.

Output

If the level is good, print the word "yes" (without the quotes), otherwise
print the word "no" (without the quotes).

"""

# Standard libraries
import unittest
import sys
import re
import random

# Additional libraries

###############################################################################
# Jump Class
###############################################################################

class Jump:
    """ Jump representation """

    def __init__(self, args):
        """ Default constructor """

        self.args = args

        self.size = args[0]
        self.maze = args[1]
        self.dist = []
        self.cur_dist = []

        self.calc_dist()

    def calc_dist(self):
        distance = 0
        start = 0
        for m in self.maze:
            if not start:
                if m:
                    start = 1
                continue
            distance += 1
            if m:
                self.dist.append(distance)
                distance = 0

    def next(self):
        self.cur_dist[1] = self.cur_dist[0] + self.cur_dist[1]
        del(self.cur_dist[0])

    def iterate(self):
        len = self.cur_dist[0]
        hop_len = 0
        hops = 0
        for m in self.cur_dist:
            hop_len += m
            if hop_len == len:
                hop_len = 0
                hops += 1
            if hops == 4:
                return 1
            if hop_len > len:
                return 0
        return 0

    def iterate_all(self):
        while len(self.cur_dist) > 1:
            if self.iterate():
                return 1
            self.next()
        return 0

    def calculate(self):
        """ Main calcualtion function of the class """

        for i in range(len(self.dist)):
            self.cur_dist = list(self.dist[i:])
            if self.iterate_all():
                return "yes"
        return "no"

###############################################################################
# Executable code
###############################################################################

def decode_inputs(inputs):
    """ Decoding input string tuple into base class args tuple """

    # Decoding first input into an integer
    size = int(inputs[0])

    # Decoding second input into a list of ints
    maze = [0 if i == "." else 1 for i in inputs[1]]
    args = (size, maze)

    return args

def calculate(inputs):
    """ Base class calculate method wrapper """
    return Jump(decode_inputs(inputs)).calculate()

def main():
    """ Main function. Not called by unit tests """

    # Read test input string tuple
    inputs = (input(), input())

    # Print the result
    print(calculate(inputs))

###############################################################################
# Unit Tests
###############################################################################

class unitTests(unittest.TestCase):

    def test_decode_inputs(self):
        """ Input string decoding testing """
        self.assertEqual(decode_inputs(("4", ".*.*")), (4, [0, 1, 0, 1]))

    def test_Jump_class__basic_functions(self):
        """ Jump class basic functions testing """
        d = Jump((7, [0, 1, 0, 1, 1, 0, 1]))
        self.assertEqual(d.size, 7)

        # Distance listb
        self.assertEqual(d.dist, [2, 1, 2])

        # Next dist merge with the next one
        d.cur_dist = [2, 1, 2]
        d.next()
        self.assertEqual(d.cur_dist, [3, 2])

        # Iterate function, 1 - success
        d.cur_dist = [2, 2, 2, 2]
        self.assertEqual(d.iterate(), 1)

        d.cur_dist = [2, 1, 1, 2, 2]
        self.assertEqual(d.iterate(), 1)

        d.cur_dist = [2, 3]
        self.assertEqual(d.iterate(), 0)

        # Iterate all possible cur_dist
        d.cur_dist = [2, 1, 3, 3, 3]
        self.assertEqual(d.iterate_all(), 1)
        d.cur_dist = [2, 1, 3, 3, 2]
        self.assertEqual(d.iterate_all(), 0)

        # Calculate
        d.dist = [20, 2, 2, 2, 2]
        # self.assertEqual(d.calculate(), "yes")

    def test_calculate(self):
        """ Main calculation function """

        # Sample test 1
        self.assertEqual(calculate(("16", ".**.*..*.***.**.")), "yes")

        # Sample test2
        self.assertEqual(calculate(("11", ".*.*...*.*.")), "no")

if __name__ == "__main__":
    if sys.argv[-1] == "-ut":
        unittest.main(argv=[" "])
    main()

```


551_B. ZgukistringZ

Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.

GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.

GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?

Input

The first line contains string a, the second line contains string b, and the third line contains string c (1 ≤ |a|, |b|, |c| ≤ 105, where |s| denotes the length of string s).

All three strings consist only of lowercase English letters.

It is possible that b and c coincide.

Output

Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.

Examples

Input

aaa
a
b

Output

aaa

Input

pozdravstaklenidodiri
niste
dobri

Output

nisteaadddiiklooprrvz

Input

abbbaaccca
ab
aca

Output

ababacabcc

Note

In the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1 – 2 (ab), 3 – 4 (ab), 5 – 7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc.

```python
from collections import defaultdict

def find_max_possible_substring(a, a_char_counts, char_counts):
    max_count_of_sub = len(a)
    for char, count in char_counts.items():
        max_count_of_sub = min(max_count_of_sub, a_char_counts[char] // char_counts[char])

    return max_count_of_sub

def get_optimal_count(a, a_orig_char_counts, max_count_of_first, first_char_counts, second_char_counts):
    max = 0
    count_of_first = 0
    count_of_second = 0
    for i in range(max_count_of_first+1):
        a_char_counts = a_orig_char_counts.copy()
        for char, count in first_char_counts.items():
            a_char_counts[char] -= count * i

        remaining_count_of_second = find_max_possible_substring(a, a_char_counts, second_char_counts)

        count = remaining_count_of_second + i
        if max < count:
            max = count
            count_of_first = i
            count_of_second = remaining_count_of_second

    return count_of_first, count_of_second

def get_result(a, a_char_counts, first, max_count_of_first, first_char_counts, second, second_char_counts):
    optimal_count_of_first, optimal_count_of_second = get_optimal_count(a, a_char_counts, max_count_of_first,
                                                                        first_char_counts, second_char_counts)
    result = ""
    result += first * optimal_count_of_first

    for char, count in first_char_counts.items():
        a_char_counts[char] -= count * optimal_count_of_first

    if optimal_count_of_second:
        result += second * optimal_count_of_second
        for char, count in second_char_counts.items():
            a_char_counts[char] -= count * optimal_count_of_second

    for char, count in a_char_counts.items():
        result += char * count

    return result

def find_k(a, b, c):
    a_char_counts = defaultdict(lambda: 0)
    b_char_counts = defaultdict(lambda: 0)
    c_char_counts = defaultdict(lambda: 0)

    for char in a:
        a_char_counts[char] += 1

    for char in b:
        b_char_counts[char] += 1

    for char in c:
        c_char_counts[char] += 1

    max_count_of_b = find_max_possible_substring(a, a_char_counts, b_char_counts)

    max_count_of_c = find_max_possible_substring(a, a_char_counts, c_char_counts)

    if max_count_of_b >= max_count_of_c:
        result = get_result(a, a_char_counts, b, max_count_of_b, b_char_counts, c, c_char_counts)
    else:
        result = get_result(a, a_char_counts, c, max_count_of_c, c_char_counts, b, b_char_counts)

    return result

if __name__ == '__main__':
    a_in = input()
    b_in = input()
    c_in = input()

    print(find_k(a_in, b_in, c_in))

```


578_C. Weakness and Poorness

You are given a sequence of n integers a1, a2, ..., an.

Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.

The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.

The poorness of a segment is defined as the absolute value of sum of the elements of segment.

Input

The first line contains one integer n (1 ≤ n ≤ 200 000), the length of a sequence.

The second line contains n integers a1, a2, ..., an (|ai| ≤ 10 000).

Output

Output a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.

Examples

Input

3
1 2 3

Output

1.000000000000000

Input

4
1 2 3 4

Output

2.000000000000000

Input

10
1 10 2 9 3 8 4 7 5 6

Output

4.500000000000000

Note

For the first case, the optimal value of x is 2 so the sequence becomes  - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case.

For the second sample the optimal value of x is 2.5 so the sequence becomes  - 1.5, - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case.

```python
""" Python 3 compatibility tools. """
from __future__ import division, print_function
import itertools
import sys
import os
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
  input = raw_input
  range = xrange

  filter = itertools.ifilter
  map = itertools.imap
  zip = itertools.izip

def is_it_local():
  script_dir = str(os.getcwd()).split('/')
  username = "dipta007"
  return username in script_dir

def READ(fileName):
  if is_it_local():
    sys.stdin = open(f'./{fileName}', 'r')

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
  newlines = 0

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

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

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

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

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

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

# endregion

def input1(type=int):
  return type(input())

def input2(type=int):
  [a, b] = list(map(type, input().split()))
  return a, b

def input3(type=int):
  [a, b, c] = list(map(type, input().split()))
  return a, b, c

def input_array(type=int):
  return list(map(type, input().split()))

def input_string():
  s = input()
  return list(s)

if is_it_local():
  def debug(*args):
    st = ""
    for arg in args:
      st += f"{arg} "
    print(st)
else:
  def debug(*args):
    pass

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

arr = []

def fun(x):
  cum = 0
  res = 0
  for v in arr:
    nw = (v-x)
    cum += nw
    cum = max(cum, 0)
    res = max(res, cum)
    # print(v, nw, cum, res)

  cum = 0
  for v in arr:
    nw = -(v-x)
    cum += nw
    cum = max(cum, 0)
    res = max(res, cum)
    # print(v, nw, cum, res)

  return res

def main():
  global arr
  n = input1()
  arr = input_array()

  low = -10000
  high = 10000
  loop = 100
  # print(fun(2.0))
  # return
  while loop > 0:
    loop -= 1

    m1 = ( low * 2.0 + high ) / 3.0
    m2 = ( low + high * 2.0) / 3.0
    y1 = fun(m1)
    y2 = fun(m2)

    # print(y1, y2)

    if y1 > y2:
      low = m1
    else:
      high = m2

  # print("res", low, high, (low + high) / 2.0)
  print(fun((low + high) / 2.0))
  pass

if __name__ == '__main__':
  # READ('in.txt')
  main()
```


5_A. Chat Server's Outgoing Traffic

Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:

  * Include a person to the chat ('Add' command).
  * Remove a person from the chat ('Remove' command).
  * Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command).

Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.

Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.

As Polycarp has no time, he is asking for your help in solving this problem.

Input

Input file will contain not more than 100 commands, each in its own line. No line will exceed 100 characters. Formats of the commands will be the following:

  * +<name> for 'Add' command.
  * -<name> for 'Remove' command.
  * <sender_name>:<message_text> for 'Send' command.

<name> and <sender_name> is a non-empty sequence of Latin letters and digits. <message_text> can contain letters, digits and spaces, but can't start or end with a space. <message_text> can be an empty line.

It is guaranteed, that input data are correct, i.e. there will be no 'Add' command if person with such a name is already in the chat, there will be no 'Remove' command if there is no person with such a name in the chat etc.

All names are case-sensitive.

Output

Print a single number — answer to the problem.

Examples

Input

+Mike
Mike:hello
+Kate
+Dmitry
-Dmitry
Kate:hi
-Kate

Output

9

Input

+Mike
-Mike
+Mike
Mike:Hi   I am here
-Mike
+Kate
-Kate

Output

14

```python
import sys
n=0
ans=0
while True:
    i=sys.stdin.readline().strip()
    if len(i)<=1:
        break
    if i[0]=="+":
        n+=1
    elif i[0]=="-":
        n-=1
    else:
        ans+=(len(i.split(':')[1]))*n
print(ans)
```


621_D. Rat Kwesh and Cheese

Wet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point.

Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers x, y and z to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options:

  1. a1 = xyz;
  2. a2 = xzy;
  3. a3 = (xy)z;
  4. a4 = (xz)y;
  5. a5 = yxz;
  6. a6 = yzx;
  7. a7 = (yx)z;
  8. a8 = (yz)x;
  9. a9 = zxy;
  10. a10 = zyx;
  11. a11 = (zx)y;
  12. a12 = (zy)x.

Let m be the maximum of all the ai, and c be the smallest index (from 1 to 12) such that ac = m. Rat's goal is to find that c, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that ac.

Input

The only line of the input contains three space-separated real numbers x, y and z (0.1 ≤ x, y, z ≤ 200.0). Each of x, y and z is given with exactly one digit after the decimal point.

Output

Find the maximum value of expression among xyz, xzy, (xy)z, (xz)y, yxz, yzx, (yx)z, (yz)x, zxy, zyx, (zx)y, (zy)x and print the corresponding expression. If there are many maximums, print the one that comes first in the list.

xyz should be outputted as x^y^z (without brackets), and (xy)z should be outputted as (x^y)^z (quotes for clarity).

Examples

Input

1.1 3.4 2.5

Output

z^y^x

Input

2.0 2.0 2.0

Output

x^y^z

Input

1.9 1.8 1.7

Output

(x^y)^z


643_B. Bear and Two Paths

Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities.

Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting each city exactly once. Formally:

  * There is no road between a and b.
  * There exists a sequence (path) of n distinct cities v1, v2, ..., vn that v1 = a, vn = b and there is a road between vi and vi + 1 for <image>.

On the other day, the similar thing happened. Limak wanted to travel between a city c and a city d. There is no road between them but there exists a sequence of n distinct cities u1, u2, ..., un that u1 = c, un = d and there is a road between ui and ui + 1 for <image>.

Also, Limak thinks that there are at most k roads in Bearland. He wonders whether he remembers everything correctly.

Given n, k and four distinct cities a, b, c, d, can you find possible paths (v1, ..., vn) and (u1, ..., un) to satisfy all the given conditions? Find any solution or print -1 if it's impossible.

Input

The first line of the input contains two integers n and k (4 ≤ n ≤ 1000, n - 1 ≤ k ≤ 2n - 2) — the number of cities and the maximum allowed number of roads, respectively.

The second line contains four distinct integers a, b, c and d (1 ≤ a, b, c, d ≤ n).

Output

Print -1 if it's impossible to satisfy all the given conditions. Otherwise, print two lines with paths descriptions. The first of these two lines should contain n distinct integers v1, v2, ..., vn where v1 = a and vn = b. The second line should contain n distinct integers u1, u2, ..., un where u1 = c and un = d.

Two paths generate at most 2n - 2 roads: (v1, v2), (v2, v3), ..., (vn - 1, vn), (u1, u2), (u2, u3), ..., (un - 1, un). Your answer will be considered wrong if contains more than k distinct roads or any other condition breaks. Note that (x, y) and (y, x) are the same road.

Examples

Input

7 11
2 4 7 3

Output

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

Input

1000 999
10 20 30 40

Output

-1

Note

In the first sample test, there should be 7 cities and at most 11 roads. The provided sample solution generates 10 roads, as in the drawing. You can also see a simple path of length n between 2 and 4, and a path between 7 and 3.

<image>

```python
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, k = map(int, input().split())
a, b, c, d = map(int, input().split())
if k < n + 1 or n == 4:
    print("-1")
    exit(0)
l = [_ for _ in range(1, n + 1)]
l.remove(a)
l.remove(b)
l.remove(c)
l.remove(d)
print(a, end = ' ')
print(c, end = ' ')
for x in l:
    print(x, end = ' ')
print(d, end = ' ')
print(b, end = ' ')
print("")
print(c, end = ' ')
print(a, end = ' ')
for x in l:
    print(x, end = ' ')
print(b, end = ' ')
print(d, end = ' ')
```


670_B. Game of Robots

In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109.

At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier.

Your task is to determine the k-th identifier to be pronounced.

Input

The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(2·109, n·(n + 1) / 2).

The second line contains the sequence id1, id2, ..., idn (1 ≤ idi ≤ 109) — identifiers of roborts. It is guaranteed that all identifiers are different.

Output

Print the k-th pronounced identifier (assume that the numeration starts from 1).

Examples

Input

2 2
1 2

Output

1

Input

4 5
10 4 18 3

Output

4

Note

In the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As k = 2, the answer equals to 1.

In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As k = 5, the answer equals to 4.

```python
n, k = input().split(' ')
n = int(n)
k = int(k)
d = input().split(' ')
i = 0

while True:
	i += 1
	p = int((i) * (i+1) / 2)
	if k <= p :
		print(d[k-(p-i)-1])
		break
```


691_D. Swaps in Permutation

You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj).

At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?

Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≤ i ≤ n exists, so pk = qk for 1 ≤ k < i and pi < qi.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 106) — the length of the permutation p and the number of pairs of positions.

The second line contains n distinct integers pi (1 ≤ pi ≤ n) — the elements of the permutation p.

Each of the last m lines contains two integers (aj, bj) (1 ≤ aj, bj ≤ n) — the pairs of positions to swap. Note that you are given a positions, not the values to swap.

Output

Print the only line with n distinct integers p'i (1 ≤ p'i ≤ n) — the lexicographically maximal permutation one can get.

Example

Input

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

Output

7 8 9 4 5 6 1 2 3

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

import os,sys
from io import BytesIO, IOBase

def solve(n,p,path):
    se, x, fin = [1] * (n + 1), 1, [0] * n
    while x != len(se):
        se[x], jj, curr, inde, vals = 0, 0, [x], [x - 1], [p[x - 1]]
        while jj != len(curr):
            zz = curr[jj]
            for y in path[zz]:
                if se[y]:
                    curr.append(y)
                    inde.append(y-1)
                    vals.append(p[y-1])
                    se[y] = 0
            jj += 1
        inde.sort()
        vals.sort()
        for ind, i in enumerate(inde):
            fin[i] = vals[-ind - 1]
        while x != n + 1 and not se[x]:
            x += 1
    for i in fin:
        print(i, end=' ')

def main():
    n, m = map(int, input().split())
    p = list(map(int, input().split()))
    path = [[] for _ in range(n + 1)]
    for _ in range(m):
        u1, v1 = map(int, input().split())
        path[u1].append(v1)
        path[v1].append(u1)
    solve(n,p,path)

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

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


716_D. Complete The Graph

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

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

Input

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

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

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

Output

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

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

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

If there are multiple solutions, print any of them.

Examples

Input

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

Output

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

Input

2 1 123456789 0 1
0 1 0

Output

YES
0 1 123456789

Input

2 1 999999999 1 0
0 1 1000000000

Output

NO

Note

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

<image>

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

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

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

```python
import heapq
from collections import defaultdict

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

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

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

    nodes = set(graph.nodes)

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

        nodes.remove(min_node)

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

    return visited, path

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

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

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

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

```


737_A. Road to Cinema

Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.

There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.

There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.

Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.

Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.

Input

The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.

Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity.

The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.

Output

Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.

Examples

Input

3 1 8 10
10 8
5 7
11 9
3

Output

10

Input

2 2 10 18
10 4
20 6
5 3

Output

20

Note

In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.

```python
# Question B. Road to Cinema
import sys

def roadToCinema(V, S, T, stations): # O(M)
    """
    V       : volume of fuel tank
    S       : total distance
    T       : time limit
    stations: fuel stations' locations

    rtype   : boolean, whether this aircraft can travel within the time limit
    """
    m = len(stations)
    t = 0
    stations.append(S) # destination
    prev = 0
    for cur in stations:
        dis = cur - prev
        # let Sa, Sb as the distance of accelerated mode/ normal mode respectively
        # then the task is:
        #  min t = (Sa + 2 * Sb)
        # s.t. Sa + Sb = dis
        #      2 * Sa + Sb <= V

        if dis > V:
            # Sa <= V - dis < 0
            return False
        else:
            # t = Sa + 2Sb = 3(Sa + Sb) - (2Sa + Sb)
            #   >= 3 * dis - V
            # on the other hand, Sb is non-negative
            # Sb = t - dis
            t += max(dis * 3 - V, dis)

        if t > T:
            return False

        prev = cur

    return True

def binSearch(S, T, stations): # O(logS * M)
    """
    to find the least tank volume to enable the aircraft to complete the journey
    the fastest way is to complete the whole journey with the speed of 2km/min, at 2L/km
    V <= 2S
    """
    l = 0
    r = S * 2

    if T < S:
        return float("inf")

    while l + 1 < r:
        m = l + (r - l) // 2
        if roadToCinema(m, S, T, stations) == True:
            r = m
        else:
            l = m

    return r

if __name__ == "__main__": # O(logS * M + N)

    line = sys.stdin.readline()
    [N, M, S, T] = list(map(int, line.split(" ")))

    aircrafts = []
    for i in range(N):
        [c, v] = list(map(int, sys.stdin.readline().split(" ")))
        aircrafts.append([c, v])

    stations = list(map(int, sys.stdin.readline().split(" ")))
    stations.sort()

    minVolume = binSearch(S, T, stations)

    if minVolume == float("inf"):
        # no aircraft can complete the journey
        print(-1)
    else:
        res = float("inf")
        for i in range(N):
            if aircrafts[i][1] >= minVolume:
                res = min(res, aircrafts[i][0])

        if res == float('inf'):
            # no given aircraft can complete the journey
            print(-1)
        else:
            print(res)
```


784_B. Kids' Riddle

Programmers' kids solve this riddle in 5-10 minutes. How fast can you do it?

Input

The input contains a single integer n (0 ≤ n ≤ 2000000000).

Output

Output a single integer.

Examples

Input

11

Output

2

Input

14

Output

0

Input

61441

Output

2

Input

571576

Output

10

Input

2128506

Output

3


805_A. Fake NP

Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.

You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.

Solve the problem to show that it's not a NP problem.

Input

The first line contains two integers l and r (2 ≤ l ≤ r ≤ 109).

Output

Print single integer, the integer that appears maximum number of times in the divisors.

If there are multiple answers, print any of them.

Examples

Input

19 29

Output

2

Input

3 6

Output

3

Note

Definition of a divisor: <https://www.mathsisfun.com/definitions/divisor-of-an-integer-.html>

The first example: from 19 to 29 these numbers are divisible by 2: {20, 22, 24, 26, 28}.

The second example: from 3 to 6 these numbers are divisible by 3: {3, 6}.

```python
n, k=map(int ,input().split())
if n==k and n%2==1:
    print(n)
else:
    print(2)
```


830_A. Office Keys

There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.

You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.

Input

The first line contains three integers n, k and p (1 ≤ n ≤ 1 000, n ≤ k ≤ 2 000, 1 ≤ p ≤ 109) — the number of people, the number of keys and the office location.

The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — positions in which people are located initially. The positions are given in arbitrary order.

The third line contains k distinct integers b1, b2, ..., bk (1 ≤ bj ≤ 109) — positions of the keys. The positions are given in arbitrary order.

Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point.

Output

Print the minimum time (in seconds) needed for all n to reach the office with keys.

Examples

Input

2 4 50
20 100
60 10 40 80

Output

50

Input

1 2 10
11
15 7

Output

7

Note

In the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.

```python
o=lambda:[int(f)for f in input().split()]
n,k,p=o()
a=sorted(o())
b=sorted(o())
print(min(max(abs(b[i + d] - a[i]) + abs(b[i + d] - p) for i in range(n)) for d in range(k - n + 1)))

```


851_B. Arpa and an exam about geometry

Arpa is taking a geometry exam. Here is the last problem of the exam.

You are given three points a, b, c.

Find a point and an angle such that if we rotate the page around the point by the angle, the new position of a is the same as the old position of b, and the new position of b is the same as the old position of c.

Arpa is doubting if the problem has a solution or not (i.e. if there exists a point and an angle satisfying the condition). Help Arpa determine if the question has a solution or not.

Input

The only line contains six integers ax, ay, bx, by, cx, cy (|ax|, |ay|, |bx|, |by|, |cx|, |cy| ≤ 109). It's guaranteed that the points are distinct.

Output

Print "Yes" if the problem has a solution, "No" otherwise.

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

Examples

Input

0 1 1 1 1 0

Output

Yes

Input

1 1 0 0 1000 1000

Output

No

Note

In the first sample test, rotate the page around (0.5, 0.5) by <image>.

In the second sample test, you can't find any solution.

```python
ax,ay,bx,by,cx,cy=map(int,input().split())
ab=(ax-bx)**2+(ay-by)**2
bc=(bx-cx)**2+(by-cy)**2
if ab==bc and (ay-by)*(bx-cx)!=(by-cy)*(ax-bx):
    print("Yes")
else:
    print("No")

```


920_E. Connected Components?

You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.

You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule.

Input

The first line contains two integers n and m (1 ≤ n ≤ 200000, <image>).

Then m lines follow, each containing a pair of integers x and y (1 ≤ x, y ≤ n, x ≠ y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices.

Output

Firstly print k — the number of connected components in this graph.

Then print k integers — the sizes of components. You should output these integers in non-descending order.

Example

Input

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

Output

2
1 4

```python
n,m=map(int,input().split())
non=[{i} for i in range(n)]
for i in range(m):
    u,v=map(int,input().split())
    u,v=u-1,v-1
    non[u].add(v)
    non[v].add(u)
vertex=set(range(n))
ans=[]
while(vertex):
    a=next(iter(vertex))
    vertex.remove(a)
    stk=[a]
    cou=1
    while(stk):
        v=stk.pop()
        s=vertex-non[v]
        cou+=len(s)
        stk.extend(s)
        vertex&=non[v]
    ans.append(cou)
ans.sort()
print(len(ans))
print(" ".join(map(str,ans)))

```


949_C. Data Center Maintenance

BigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!).

Main feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers.

For each of m company clients, let us denote indices of two different data centers storing this client data as ci, 1 and ci, 2.

In order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day.

Data center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly h hours long. For each data center there is an integer uj (0 ≤ uj ≤ h - 1) defining the index of an hour of day, such that during this hour data center j is unavailable due to maintenance.

Summing up everything above, the condition uci, 1 ≠ uci, 2 should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance.

Due to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for them by an hour later (i.e. if uj = h - 1, then the new maintenance hour would become 0, otherwise it would become uj + 1). Nonetheless, such an experiment should not break the accessibility guarantees, meaning that data of any client should be still available during any hour of a day after the data center maintenance times are changed.

Such an experiment would provide useful insights, but changing update time is quite an expensive procedure, that is why the company asked you to find out the minimum number of data centers that have to be included in an experiment in order to keep the data accessibility guarantees.

Input

The first line of input contains three integers n, m and h (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000, 2 ≤ h ≤ 100 000), the number of company data centers, number of clients and the day length of day measured in hours.

The second line of input contains n integers u1, u2, ..., un (0 ≤ uj < h), j-th of these numbers is an index of a maintenance hour for data center j.

Each of the next m lines contains two integers ci, 1 and ci, 2 (1 ≤ ci, 1, ci, 2 ≤ n, ci, 1 ≠ ci, 2), defining the data center indices containing the data of client i.

It is guaranteed that the given maintenance schedule allows each client to access at least one copy of his data at any moment of day.

Output

In the first line print the minimum possible number of data centers k (1 ≤ k ≤ n) that have to be included in an experiment in order to keep the data available for any client.

In the second line print k distinct integers x1, x2, ..., xk (1 ≤ xi ≤ n), the indices of data centers whose maintenance time will be shifted by one hour later. Data center indices may be printed in any order.

If there are several possible answers, it is allowed to print any of them. It is guaranteed that at there is at least one valid choice of data centers.

Examples

Input

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

Output

1
3

Input

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

Output

4
1 2 3 4

Note

Consider the first sample test. The given answer is the only way to conduct an experiment involving the only data center. In such a scenario the third data center has a maintenance during the hour 1, and no two data centers storing the information of the same client have maintenance at the same hour.

On the other hand, for example, if we shift the maintenance time on hour later for the first data center, then the data of clients 1 and 3 will be unavailable during the hour 0.

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

n, m, MOD = map(int, input().split())
u = list(map(int, input().split()))
info = [list(map(int, input().split())) for i in range(m)]

graph = [[] for i in range(n)]
rev_graph = [[] for i in range(n)]
set_ = set()
INF = 10 ** 9
for a, b in info:
    a -= 1
    b -= 1
    if (u[a] + 1) % MOD == u[b]:
        if a * INF + b not in set_:
            graph[a].append(b)
            rev_graph[b].append(a)
            set_.add(a * INF + b)
    if (u[b] + 1) % MOD == u[a]:
        if b * INF + a not in set_:
            graph[b].append(a)
            rev_graph[a].append(b)
            set_.add(b * INF + a)

def scc(N, G, RG):
    order = []
    used = [0]*N
    group = [None]*N
    def dfs(s):
        used[s] = 1
        q = deque([s])
        tmp = deque([s])
        while q:
            s = q.pop()
            for t in G[s]:
                if not used[t]:
                    used[t] = 1
                    q.append(t)
                    tmp.append(t)
        while tmp:
            order.append(tmp.pop())
    def rdfs(s, col):
        group[s] = col
        used[s] = 1
        q = deque([s])
        while q:
            s = q.pop()
            for t in RG[s]:
                if not used[t]:
                    q.append(t)
                    used[t] = 1
                    group[t] = col
    for i in range(N):
        if not used[i]:
            dfs(i)
    used = [0]*N
    label = 0
    for s in reversed(order):
        if not used[s]:
            rdfs(s, label)
            label += 1
    return label, group

def construct(N, G, label, group):
    G0 = [set() for i in range(label)]
    GP = [[] for i in range(label)]
    for v in range(N):
        lbs = group[v]
        for w in G[v]:
            lbt = group[w]
            if lbs == lbt:
                continue
            G0[lbs].add(lbt)
        GP[lbs].append(v + 1)
    return G0, GP

min_ans = 10 ** 9
ind_ans = -1
label, group = scc(n, graph, rev_graph)
new_graph, element = construct(n, graph, label, group)
for i in range(len(new_graph)):
    if len(new_graph[i]) == 0 and min_ans > len(element[i]):
        min_ans = len(element[i])
        ind_ans = i

print(min_ans)
print(*element[ind_ans])

```


977_B. Two-gram

Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams.

You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string s = "BBAABBBA" the answer is two-gram "BB", which contained in s three times. In other words, find any most frequent two-gram.

Note that occurrences of the two-gram can overlap with each other.

Input

The first line of the input contains integer number n (2 ≤ n ≤ 100) — the length of string s. The second line of the input contains the string s consisting of n capital Latin letters.

Output

Print the only line containing exactly two capital Latin letters — any two-gram contained in the given string s as a substring (i.e. two consecutive characters of the string) maximal number of times.

Examples

Input

7
ABACABA

Output

AB

Input

5
ZZZAA

Output

ZZ

Note

In the first example "BA" is also valid answer.

In the second example the only two-gram "ZZ" can be printed because it contained in the string "ZZZAA" two times.

```python
n = int(input())
k = str(input())
Max = 0
for i in range(n-1):
    t=k[i]+k[i+1]
    z=0
    for j in range(0,n-1):
        s=k[j]+k[j+1]
        if (s==t):
            z=z+1
    #print(z)
    if (z>Max):
        Max=z
        res=t
print(res)

```


996_F. Game

Allen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n → R, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, ..., x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an i such that x_i = -1 and either setting x_i → 0 or x_i → 1.

After n rounds all variables are set, and the game value resolves to f(x_1, x_2, ..., x_n). Allen wants to maximize the game value, and Bessie wants to minimize it.

Your goal is to help Allen and Bessie find the expected game value! They will play r+1 times though, so between each game, exactly one value of f changes. In other words, between rounds i and i+1 for 1 ≤ i ≤ r, f(z_1, ..., z_n) → g_i for some (z_1, ..., z_n) ∈ \{0, 1\}^n. You are to find the expected game value in the beginning and after each change.

Input

The first line contains two integers n and r (1 ≤ n ≤ 18, 0 ≤ r ≤ 2^{18}).

The next line contains 2^n integers c_0, c_1, ..., c_{2^n-1} (0 ≤ c_i ≤ 10^9), denoting the initial values of f. More specifically, f(x_0, x_1, ..., x_{n-1}) = c_x, if x = \overline{x_{n-1} … x_0} in binary.

Each of the next r lines contains two integers z and g (0 ≤ z ≤ 2^n - 1, 0 ≤ g ≤ 10^9). If z = \overline{z_{n-1} ... z_0} in binary, then this means to set f(z_0, ..., z_{n-1}) → g.

Output

Print r+1 lines, the i-th of which denotes the value of the game f during the i-th round. Your answer must have absolute or relative error within 10^{-6}.

Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac{|a - b|}{max{(1, |b|)}} ≤ 10^{-6}.

Examples

Input

2 2
0 1 2 3
2 5
0 4

Output

1.500000
2.250000
3.250000

Input

1 0
2 3

Output

2.500000

Input

2 0
1 1 1 1

Output

1.000000

Note

Consider the second test case. If Allen goes first, he will set x_1 → 1, so the final value will be 3. If Bessie goes first, then she will set x_1 → 0 so the final value will be 2. Thus the answer is 2.5.

In the third test case, the game value will always be 1 regardless of Allen and Bessie's play.

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

import time

(n, r) = (int(i) for i in input().split())
c      = [int(i) for i in input().split()]

start = time.time()

s  = sum(c)
n2 = 2**n

ans = [s/n2]
for i in range(r):
    (k, new) = (int(i) for i in input().split())
    s       += new - c[k]
    c[k]     = new
    ans.append(s/n2)

for i in range(len(ans)):
    print(ans[i])

finish = time.time()
#print(finish - start)

```


p02652 AtCoder Grand Contest 045 - 01 Unbalanced

Given is a string S, where each character is `0`, `1`, or `?`.

Consider making a string S' by replacing each occurrence of `?` with `0` or `1` (we can choose the character for each `?` independently). Let us define the unbalancedness of S' as follows:

* (The unbalancedness of S') = \max \\{ The absolute difference between the number of occurrences of `0` and `1` between the l-th and r-th character of S (inclusive) :\ 1 \leq l \leq r \leq |S|\\}

Find the minimum possible unbalancedness of S'.

Constraints

* 1 \leq |S| \leq 10^6
* Each character of S is `0`, `1`, or `?`.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum possible unbalancedness of S'.

Examples

Input

0??

Output

1

Input

0??0

Output

2

Input

??00????0??0????0?0??00??1???11?1?1???1?11?111???1

Output

4

```python
from itertools import accumulate

S = input()
N = len(S)

A = [0] + list(accumulate(1 if s == "1" else -1 for s in S))

ma = max(A)
cur = A[-1]
C = [ma - cur]
for a in reversed(A):
    cur = max(a, cur)
    C.append(ma - cur)

d, e = 0, 0
D, E = A[:], A[:]
for i, (s, c) in enumerate(zip(S, reversed(C[:-1])), 1):
    if s == '?' and c >= d + 2:
        d += 2
    if s == '?' and c >= e + 1:
        e += 2
    D[i] += d
    E[i] += e

print(min(max(D) - min(D), max(E) - min(E)))
```