### Prompt

In Cpp, your task is to solve the following problem:

A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".

The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west to east. The lot has n + 1 dividing lines drawn from west to east and m + 1 dividing lines drawn from north to south, which divide the parking lot into n·m 4 by 4 meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from 0 to n from north to south and from 0 to m from west to east. Each square has coordinates (i, j) so that the square in the north-west corner has coordinates (1, 1) and the square in the south-east corner has coordinates (n, m). See the picture in the notes for clarifications.

Before the game show the organizers offer Yura to occupy any of the (n + 1)·(m + 1) intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" c placed in a square whose center is at distance d from Yura takes c·d2 seconds. The time Yura spends on turning his head can be neglected.

It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the sizes of the parking lot. Each of the next n lines contains m integers: the j-th number in the i-th line describes the "rarity" cij (0 ≤ cij ≤ 100000) of the car that is located in the square with coordinates (i, j).

Output

In the first line print the minimum total time Yura needs to guess all offered cars. In the second line print two numbers li and lj (0 ≤ li ≤ n, 0 ≤ lj ≤ m) — the numbers of dividing lines that form a junction that Yura should choose to stand on at the beginning of the game show. If there are multiple optimal starting points, print the point with smaller li. If there are still multiple such points, print the point with smaller lj.

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

Examples

Input

2 3
3 4 5
3 9 1

Output

392
1 1

Input

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

Output

240
2 3

Note

In the first test case the total time of guessing all cars is equal to 3·8 + 3·8 + 4·8 + 9·8 + 5·40 + 1·40 = 392.

The coordinate system of the field:

<image>

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int toInt(string s) {
  istringstream sin(s);
  int t;
  sin >> t;
  return t;
}
template <class T>
string toString(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}
template <class T>
void chmin(T &t, T f) {
  if (t > f) t = f;
}
template <class T>
void chmax(T &t, T f) {
  if (t < f) t = f;
}
int g[1010][1010];
long long row[1010], col[1010];
int main() {
  int n, m;
  int i, j;
  cin >> n >> m;
  for (i = (0); i < (n); i++)
    for (j = (0); j < (m); j++) {
      cin >> g[i][j];
      row[i] += g[i][j];
      col[j] += g[i][j];
    }
  long long mn1, mn2;
  mn1 = mn2 = 1ll << 61;
  int p1, p2;
  for (i = (0); i < (n + 1); i++) {
    long long sum = 0;
    for (j = (0); j < (n); j++) {
      long long d = 2 + 4ll * j - 4ll * i;
      sum += d * d * row[j];
    }
    if (sum < mn1) {
      mn1 = sum;
      p1 = i;
    }
  }
  for (i = (0); i < (m + 1); i++) {
    long long sum = 0;
    for (j = (0); j < (m); j++) {
      long long d = 2 + 4ll * j - 4ll * i;
      sum += d * d * col[j];
    }
    if (sum < mn2) {
      mn2 = sum;
      p2 = i;
    }
  }
  cout << mn1 + mn2 << endl;
  cout << p1 << " " << p2 << endl;
  return 0;
}

```


### Prompt

Develop a solution in CPP to the problem described below:

The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these.

According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situation is possible, and if it is, find a possible set of bills contained in the envelope. Assume that his grandfather is rich enough, and the envelope was large enough.

Constraints

* 1 ≤ N ≤ 2000
* 1000 ≤ Y ≤ 2 × 10^7
* N is an integer.
* Y is a multiple of 1000.

Input

Input is given from Standard Input in the following format:

N Y

Output

If the total value of N bills cannot be Y yen, print `-1 -1 -1`.

If the total value of N bills can be Y yen, let one such set of bills be "x 10000-yen bills, y 5000-yen bills and z 1000-yen bills", and print x, y, z with spaces in between. If there are multiple possibilities, any of them may be printed.

Examples

Input

9 45000

Output

4 0 5

Input

20 196000

Output

-1 -1 -1

Input

1000 1234000

Output

14 27 959

Input

2000 20000000

Output

2000 0 0

### Response

```cpp
#include <iostream>
using namespace std;

int main()
{
	int n,y,k;
	cin>>n>>y;
	for(int i=0; i<=y/10000; i++){
		for(int j=0; j<=y/5000; j++){
			k=n-i-j;
			if(k>=0 && i*10000+j*5000+k*1000==y){
				cout<<i<<" "<<j<<" "<<k<<endl;
				return 0;
			}
		}
	}
	cout<<"-1 -1 -1"<<endl;

	return 0;
}
```


### Prompt

Your challenge is to write a CPP solution to the following problem:

There are n parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely r_i. When a parrot with respect level x starts chattering, x neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on, until all the birds begin to chatter.

You are given the respect levels of all parrots. For each parrot answer a question: if this certain parrot starts chattering, how many seconds will pass until all other birds will start repeating it?

Input

In the first line of input there is a single integer n, the number of parrots (1 ≤ n ≤ 10^5).

In the next line of input there are n integers r_1, ..., r_n, the respect levels of parrots in order they stand in the circle (1 ≤ r_i ≤ n).

Output

Print n integers. i-th of them should equal the number of seconds that is needed for all parrots to start chattering if the i-th parrot is the first to start.

Examples

Input

4
1 1 4 1

Output

2 2 1 2

Input

8
1 2 2 1 5 1 3 1

Output

3 3 2 2 1 2 2 3

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 10;
const int inf = 1e9;
int gi() {
  int x = 0, o = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') o = -1, ch = getchar();
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  return x * o;
}
int n, m, a[N];
pair<int, int> f[N][20];
pair<int, int> operator+(pair<int, int> a, pair<int, int> b) {
  return make_pair(min(a.first, b.first), max(a.second, b.second));
}
struct segtree {
  pair<int, int> tr[N << 2];
  void build(int o, int l, int r, int k) {
    if (l == r) {
      tr[o] = f[l][k];
      return;
    }
    int mid = (l + r) >> 1;
    build((o << 1), l, mid, k);
    build((o << 1 | 1), mid + 1, r, k);
    tr[o] = tr[(o << 1)] + tr[(o << 1 | 1)];
  }
  pair<int, int> query(int o, int l, int r, int L, int R) {
    if (L <= l && r <= R) return tr[o];
    int mid = (l + r) >> 1;
    pair<int, int> ret = make_pair(inf, -inf);
    if (L <= mid) ret = ret + query((o << 1), l, mid, L, R);
    if (R > mid) ret = ret + query((o << 1 | 1), mid + 1, r, L, R);
    return ret;
  }
} tr[20];
int main() {
  n = gi();
  if (n == 1) return puts("0"), 0;
  for (int i = 1; i <= n; i++) a[i] = a[i + n] = a[i + n + n] = gi();
  m = 3 * n;
  for (int i = 1; i <= m; i++)
    f[i][0] = make_pair(max(1, i - a[i]), min(m, i + a[i]));
  for (int j = 1; j <= 19; j++) {
    tr[j - 1].build(1, 1, m, j - 1);
    for (int i = 1; i <= m; i++)
      f[i][j] = tr[j - 1].query(1, 1, m, f[i][j - 1].first, f[i][j - 1].second);
  }
  tr[19].build(1, 1, m, 19);
  for (int i = n + 1; i <= n + n; i++) {
    int ans = 0, l = i, r = i;
    for (int j = 19; j >= 0; j--) {
      pair<int, int> x = tr[j].query(1, 1, m, l, r);
      if (x.second - x.first + 1 < n)
        l = x.first, r = x.second, ans += (1 << j);
    }
    printf("%d ", ans + 1);
  }
  return 0;
}

```


### Prompt

Construct a Cpp code solution to the problem outlined:

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s.

Constraints

* 1 ≤ H, W ≤ 1,400

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest rectangle.

Example

Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Output

6

### Response

```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;

struct Rectangle {
	int h;
	int p;  // position from left
};

int max_area_of_histgram(int n, vector<int>& height) {
	stack<Rectangle> S;

	/*	initialize	*/
	int maxv = 0;

	for (int i = 0; i <= n; i++) {
		Rectangle rect;
		rect.h = height[i];
		rect.p = i;

		if (S.empty()) {
			S.push(rect);
		}
		else if (S.top().h < rect.h) {
			S.push(rect);
		}
		else if (S.top().h > rect.h) {
			int now = i;
			while (!(S.empty()) && (S.top().h >= rect.h)) {
				Rectangle pre_rect = S.top(); S.pop();
				maxv = max(maxv, pre_rect.h * (i - pre_rect.p));
				now = pre_rect.p;
			}
			rect.p = now;
			S.push(rect);
		}
	}
	return maxv;
}

int get_Largest_Rectangle(int H,int W,vector<vector<int>>& dp) {
	for (int h = 1; h < H; h++) {
		for (int w = 0; w < W; w++) {
			if (dp[h][w] == 0) continue;
			dp[h][w] = dp[h - 1][w] + 1;
		}
	}

	int maxv = 0;
	for (int h = 0; h < H; h++) {
		maxv = max(maxv, max_area_of_histgram(W, dp[h]));
	}
	return maxv;
}
int main() {
	cin.tie(0); ios::sync_with_stdio(false);
	int H, W; cin >> H >> W;
	vector<vector<int>> c(H + 1, vector<int>(W + 1,0)), dp(H + 1, vector<int>(W + 1,0));

	for (int h = 0; h < H; h++) {
		for (int w = 0; w < W; w++) {
			cin >> c[h][w];
			if (c[h][w] == 0) { dp[h][w] = 1; }
			else { dp[h][w] = 0; }
		}
	}
	cout << get_Largest_Rectangle(H, W, dp) << endl;
}
```


### Prompt

Please create a solution in cpp to the following problem:

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

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

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

Input

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

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

Output

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

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

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

Examples

Input

4
0 0
0 1
1 1
1 0

Output

0.3535533906

Input

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

Output

1.0000000000

Note

Here is a picture of the first sample

<image>

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

<image>

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

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
const int MAXK = 300;
const double INF = 1e18 + 10;
const double EPS = 1e-6;
int n;
long long x[MAXN], y[MAXN];
double dist(int l, int mid, int r) {
  long long mul =
      (x[mid] - x[l]) * (y[r] - y[l]) - (x[r] - x[l]) * (y[mid] - y[l]);
  return abs(mul) / sqrt(((y[r] - y[l]) * (y[r] - y[l])) +
                         ((x[r] - x[l]) * (x[r] - x[l])));
}
int main() {
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> x[i] >> y[i];
  }
  double ans = INF;
  for (int i = 0; i < n; ++i) {
    ans = min(ans, dist(i, (i + 1) % n, (i + 2) % n));
  }
  printf("%.8f", ans / 2);
  return 0;
}

```


### Prompt

In cpp, your task is to solve the following problem:

Your company’s next product will be a new game, which is a three-dimensional variant of the classic game “Tic-Tac-Toe”. Two players place balls in a three-dimensional space (board), and try to make a sequence of a certain length.

People believe that it is fun to play the game, but they still cannot fix the values of some parameters of the game. For example, what size of the board makes the game most exciting? Parameters currently under discussion are the board size (we call it n in the following) and the length of the sequence (m). In order to determine these parameter values, you are requested to write a computer simulator of the game.

You can see several snapshots of the game in Figures 1-3. These figures correspond to the three datasets given in the Sample Input.

<image>

Figure 1: A game with n = m = 3

Here are the precise rules of the game.

1. Two players, Black and White, play alternately. Black plays first.
2. There are n × n vertical pegs. Each peg can accommodate up to n balls. A peg can be specified by its x- and y-coordinates (1 ≤ x, y ≤ n). A ball on a peg can be specified by its z-coordinate (1 ≤ z ≤ n). At the beginning of a game, there are no balls on any of the pegs.

<image>

Figure 2: A game with n = m = 3 (White made a 3-sequence before Black)

3. On his turn, a player chooses one of n × n pegs, and puts a ball of his color onto the peg. The ball follows the law of gravity. That is, the ball stays just above the top-most ball on the same peg or on the floor (if there are no balls on the peg). Speaking differently, a player can choose x- and y-coordinates of the ball, but he cannot choose its z-coordinate.
4. The objective of the game is to make an m-sequence. If a player makes an m-sequence or longer of his color, he wins. An m-sequence is a row of m consecutive balls of the same color. For example, black balls in positions (5, 1, 2), (5, 2, 2) and (5, 3, 2) form a 3-sequence. A sequence can be horizontal, vertical, or diagonal. Precisely speaking, there are 13 possible directions to make a sequence, categorized as follows.

<image>

Figure 3: A game with n = 4, m = 3 (Black made two 4-sequences)

(a) One-dimensional axes. For example, (3, 1, 2), (4, 1, 2) and (5, 1, 2) is a 3-sequence. There are three directions in this category.
(b) Two-dimensional diagonals. For example, (2, 3, 1), (3, 3, 2) and (4, 3, 3) is a 3-sequence. There are six directions in this category.
(c) Three-dimensional diagonals. For example, (5, 1, 3), (4, 2, 4) and (3, 3, 5) is a 3- sequence. There are four directions in this category.

Note that we do not distinguish between opposite directions.

As the evaluation process of the game, people have been playing the game several times changing the parameter values. You are given the records of these games. It is your job to write a computer program which determines the winner of each recorded game.

Since it is difficult for a human to find three-dimensional sequences, players often do not notice the end of the game, and continue to play uselessly. In these cases, moves after the end of the game, i.e. after the winner is determined, should be ignored. For example, after a player won making an m-sequence, players may make additional m-sequences. In this case, all m-sequences but the first should be ignored, and the winner of the game is unchanged.

A game does not necessarily end with the victory of one of the players. If there are no pegs left to put a ball on, the game ends with a draw. Moreover, people may quit a game before making any m-sequence. In such cases also, the game ends with a draw.

Input

The input consists of multiple datasets each corresponding to the record of a game. A dataset starts with a line containing three positive integers n, m, and p separated by a space. The relations 3 ≤ m ≤ n ≤ 7 and 1 ≤ p ≤ n3 hold between them. n and m are the parameter values of the game as described above. p is the number of moves in the game.

The rest of the dataset is p lines each containing two positive integers x and y. Each of these lines describes a move, i.e. the player on turn puts his ball on the peg specified. You can assume that 1 ≤ x ≤ n and 1 ≤ y ≤ n. You can also assume that at most n balls are put on a peg throughout a game.

The end of the input is indicated by a line with three zeros separated by a space.

Output

For each dataset, a line describing the winner and the number of moves until the game ends should be output. The winner is either “Black” or “White”. A single space should be inserted between the winner and the number of moves. No other extra characters are allowed in the output.

In case of a draw, the output line should be “Draw”.

Example

Input

3 3 3
1 1
1 1
1 1
3 3 7
2 2
1 3
1 1
2 3
2 1
3 3
3 1
4 3 15
1 1
2 2
1 1
3 3
3 3
1 1
3 3
3 3
4 4
1 1
4 4
4 4
4 4
4 1
2 2
0 0 0

Output

Draw
White 6
Black 15

### Response

```cpp
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <cassert>
#include <string>
#include <memory.h>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <set>
#include <map>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <cctype>
#include <fstream>
#include <cmath>
using namespace std;

#define REP2(i, m, n) for(int i = (int)(m); i < (int)(n); i++)
#define REP(i, n) REP2(i, 0, n)
#define ALL(c) (c).begin(), (c).end()
#define ITER(c) __typeof((c).begin())
#define PB(e) push_back(e)
#define FOREACH(i, c) for(ITER(c) i = (c).begin(); i != (c).end(); ++i)
#define MP(a, b) make_pair(a, b)
#define PARITY(n) ((n) & 1)

typedef long long ll;
typedef pair<ll, ll> P;
const int INF = 1000 * 1000 * 1000 + 7;
const double EPS = 1e-10;

int n,m, p;
const int sz = 10;
int board [sz][sz][sz];
int height[sz][sz];

bool win(int _x, int _y, int _z, int c){
  for(int dx = -1; dx <= 1; dx++){
    for(int dy = -1; dy <= 1; dy++){
      for(int dz = -1; dz <= 1; dz++){
        if(dx == 0 && dy == 0 && dz == 0) continue;
        int x = _x, y = _y, z = _z;
        int count = -1;

        while(board[x][y][z] == c && count < m){
          x += dx;
          y += dy;
          z += dz;
          count++;
        }
        x = _x, y = _y, z = _z;
        while(board[x][y][z] == c && count < m){
          x -= dx;
          y -= dy;
          z -= dz;
          count++;
        }
        if(count == m) return true;
      }
    }
  }
  return false;
}

void solve(const vector<int> &xs, const vector<int> &ys){
  REP(i, xs.size()){
    int x = xs[i];
    int y = ys[i];
    board[x][y][++height[x][y]] = i % 2;
    if(win(x, y, height[x][y], i % 2)){
      cout << (i % 2 == 0 ? "Black " : "White ") << i + 1<< endl;
      return;
    }
  }
    cout << "Draw" << endl;
}

int main(){
  while(cin >> n >> m >> p && n + m + p > 0){
    int x, y;
    memset(board, -1, sizeof(board));
    memset(height, 0, sizeof(height));
    vector<int> xs;
    vector<int> ys;
    REP(i, p){
      cin >> x >> y;
      xs.push_back(x);
      ys.push_back(y);
    }
    solve(xs, ys);
  }
  return 0;
}
```


### Prompt

Create a solution in Cpp for the following problem:

Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.

Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).

Your task is to count the number of segments where Horace can "see an elephant".

Input

The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.

Output

Print the number of segments in the bears' wall where Horace can "see an elephant".

Examples

Input

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

Output

2

Note

The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.

<image>

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int F[N] = {-1}, A[N], B[N];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++) cin >> A[i];
  for (int i = n - 1; i >= 1; i--) A[i] = A[i] - A[i - 1];
  A[0] = 0;
  for (int i = 0; i < m; i++) cin >> B[i];
  for (int i = m - 1; i >= 1; i--) B[i] = B[i] - B[i - 1];
  if (m == 1) {
    cout << n << endl;
    return 0;
  }
  for (int i = 1; i < m; i++) B[i - 1] = B[i];
  m--;
  for (int i = 1; i < m; i++) {
    int j = F[i - 1];
    while (B[j + 1] != B[i] && j >= 0) j = F[j];
    if (B[j + 1] == B[i])
      F[i] = j + 1;
    else
      F[i] = -1;
  }
  int cnt = 0;
  int i = 1, j = 0;
  while (i < n) {
    if (A[i] == B[j]) {
      i++;
      j++;
      if (j == m) {
        cnt++;
        j = F[j - 1] + 1;
      }
    } else {
      if (j == 0)
        i++;
      else
        j = F[j - 1] + 1;
    }
  }
  cout << cnt << endl;
  return 0;
}

```


### Prompt

Construct a CPP code solution to the problem outlined:

This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.

He decided to accomplish this by closing every k-th (2 ≤ k ≤ n - 1) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be b) and then close all tabs with numbers c = b + i ⋅ k that satisfy the following condition: 1 ≤ c ≤ n and i is an integer (it may be positive, negative or zero).

For example, if k = 3, n = 14 and Roman chooses b = 8, then he will close tabs with numbers 2, 5, 8, 11 and 14.

After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it e) and the amount of remaining social network tabs (s). Help Roman to calculate the maximal absolute value of the difference of those values |e - s| so that it would be easy to decide what to do next.

Input

The first line contains two integers n and k (2 ≤ k < n ≤ 100) — the amount of tabs opened currently and the distance between the tabs closed.

The second line consists of n integers, each of them equal either to 1 or to -1. The i-th integer denotes the type of the i-th tab: if it is equal to 1, this tab contains information for the test, and if it is equal to -1, it's a social network tab.

Output

Output a single integer — the maximum absolute difference between the amounts of remaining tabs of different types |e - s|.

Examples

Input

4 2
1 1 -1 1

Output

2

Input

14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1

Output

9

Note

In the first example we can choose b = 1 or b = 3. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, e = 2 and s = 0 and |e - s| = 2.

In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.

### Response

```cpp
#include <bits/stdc++.h>
int main() {
  int n, k;
  scanf("%d%d", &n, &k);
  std::vector<int> tabs(n);
  for (int i = 0; i < n; i++) scanf("%d", &tabs[i]);
  std::vector<int> res;
  for (int i = 0; i < k; i++) {
    std::vector<int> a(tabs);
    for (int j = i; j < n; j += k) a[j] = 0;
    int e = std::count(a.begin(), a.end(), 1);
    int s = std::count(a.begin(), a.end(), -1);
    res.push_back(std::max(std::abs(e - s), std::abs(s - e)));
  }
  printf("%d\n", *std::max_element(res.begin(), res.end()));
  return 0;
}

```


### Prompt

Please create a solution in cpp to the following problem:

There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.

For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.

The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.

There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?

Formally, we assume that two words denote the same name, if using the replacements "u" <image> "oo" and "h" <image> "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.

For example, the following pairs of words denote the same name:

  * "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper" <image> "kuuper" and "kuooper" <image> "kuuper".
  * "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun" <image> "khoon" and "kkkhoon" <image> "kkhoon" <image> "khoon".

For a given list of words, find the minimal number of groups where the words in each group denote the same name.

Input

The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list.

The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.

Output

Print the minimal number of groups where the words in each group denote the same name.

Examples

Input

10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon

Output

4

Input

9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi

Output

5

Input

2
alex
alex

Output

1

Note

There are four groups of words in the first example. Words in each group denote same name:

  1. "mihail", "mikhail"
  2. "oolyana", "ulyana"
  3. "kooooper", "koouper"
  4. "hoon", "khun", "kkkhoon"

There are five groups of words in the second example. Words in each group denote same name:

  1. "hariton", "kkkhariton", "khariton"
  2. "hkariton"
  3. "buoi", "boooi", "boui"
  4. "bui"
  5. "boi"

In the third example the words are equal, so they denote the same name.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, i, j;
  cin >> n;
  string p = "";
  vector<string> s(n);
  for (i = 0; i < n; i++) cin >> s[i];
  for (j = 0; j < n; j++) {
    p = s[j];
    if (p == "u") p = "oo";
    for (i = 1; i < p.length(); i++) {
      if (p[i - 1] == 'u') {
        p = p.substr(0, i - 1) + "oo" + p.substr(i, p.length());
      }
      if (p[p.length() - 1] == 'u') p = p.substr(0, p.length() - 1) + "oo";
      if (p[i - 1] == 'k' && p[i] == 'h') {
        p = p.substr(0, i - 1) + p.substr(i, p.length());
        i = 0;
      }
    }
    s[j] = p;
    p = "";
  }
  sort(s.begin(), s.end());
  s.erase(unique(s.begin(), s.end()), s.end());
  cout << s.size();
  return 0;
}

```


### Prompt

In CPP, your task is to solve the following problem:

We have N logs of lengths A_1,A_2,\cdots A_N.

We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.

Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.

Constraints

* 1 \leq N \leq 2 \times 10^5
* 0 \leq K \leq 10^9
* 1 \leq A_i \leq 10^9
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print an integer representing the answer.

Examples

Input

2 3
7 9

Output

4

Input

3 0
3 4 5

Output

5

Input

10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202

Output

292638192

### Response

```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=200005;
ll n,k,a[maxn],maxv;
int check(int len)
{
	if(!len)
		return 1e9+1;
	ll num=0;
	for(int i=1;i<=n;i++)
		num+=(a[i]-1)/len;
	return num;
}
int main()
{
	cin>>n>>k;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		maxv=max(maxv,a[i]);
	}
	int l=0,r=maxv;
	while(l<r)
	{
		int mid=(l+r)/2;
		if(check(mid)>k)
			l=mid+1;
		else
			r=mid;
	}
	cout<<l<<endl;
    return 0;
}

```


### Prompt

Please formulate a CPP solution to the following problem:

Boboniu likes bit operations. He wants to play a game with you.

Boboniu gives you two sequences of non-negative integers a_1,a_2,…,a_n and b_1,b_2,…,b_m.

For each i (1≤ i≤ n), you're asked to choose a j (1≤ j≤ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). Note that you can pick the same j for different i's.

Find the minimum possible c_1 | c_2 | … | c_n, where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).

Input

The first line contains two integers n and m (1≤ n,m≤ 200).

The next line contains n integers a_1,a_2,…,a_n (0≤ a_i < 2^9).

The next line contains m integers b_1,b_2,…,b_m (0≤ b_i < 2^9).

Output

Print one integer: the minimum possible c_1 | c_2 | … | c_n.

Examples

Input

4 2
2 6 4 0
2 4

Output

2

Input

7 6
1 9 1 9 8 1 0
1 1 4 5 1 4

Output

0

Input

8 5
179 261 432 162 82 43 10 38
379 357 202 184 197

Output

147

Note

For the first example, we have c_1=a_1\& b_2=0, c_2=a_2\& b_1=2, c_3=a_3\& b_1=0, c_4 = a_4\& b_1=0.Thus c_1 | c_2 | c_3 |c_4 =2, and this is the minimal answer we can get.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int a[201], b[201];
int n, m;
int OO = 1e9;
int dp[201][10000];
int ansr = OO;
void solve(int i, int ans) {
  if (i == n) {
    ansr = min(ansr, ans);
    return;
  }
  int &ret = dp[i][ans];
  if (ret != -1) return;
  ret = 1;
  for (int j = 0; j < m; j++) {
    solve(i + 1, ((a[i] & b[j]) | ans));
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n >> m;
  memset(dp, -1, sizeof dp);
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  for (int i = 0; i < m; i++) {
    cin >> b[i];
  }
  solve(0, 0);
  cout << ansr;
  return 0;
}

```


### Prompt

In cpp, your task is to solve the following problem:

There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.

You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).

If two districts belonging to the same gang are connected directly with a road, this gang will revolt.

You don't want this so your task is to build n-1 two-way roads in such a way that all districts are reachable from each other (possibly, using intermediate districts) and each pair of directly connected districts belong to different gangs, or determine that it is impossible to build n-1 roads to satisfy all the conditions.

You have to answer t independent test cases.

Input

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

The first line of the test case contains one integer n (2 ≤ n ≤ 5000) — the number of districts. The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the gang the i-th district belongs to.

It is guaranteed that the sum of n does not exceed 5000 (∑ n ≤ 5000).

Output

For each test case, print:

  * NO on the only line if it is impossible to connect all districts satisfying the conditions from the problem statement.
  * YES on the first line and n-1 roads on the next n-1 lines. Each road should be presented as a pair of integers x_i and y_i (1 ≤ x_i, y_i ≤ n; x_i ≠ y_i), where x_i and y_i are two districts the i-th road connects.

For each road i, the condition a[x_i] ≠ a[y_i] should be satisfied. Also, all districts should be reachable from each other (possibly, using intermediate districts).

Example

Input

4
5
1 2 2 1 3
3
1 1 1
4
1 1000 101 1000
4
1 2 3 4

Output

YES
1 3
3 5
5 4
1 2
NO
YES
1 2
2 3
3 4
YES
1 2
1 3
1 4

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
vector<vector<long long>> g;
vector<long long> used;
vector<pair<long long, long long>> ans;
void dfs(long long o) {
  used[o] = 1;
  long long i;
  for (i = 0; i < g.size(); i++)
    if (g[o][i] && !used[i]) {
      ans.push_back(make_pair(o + 1, i + 1));
      dfs(i);
    }
}
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, i, j, t = 1;
    cin >> n;
    vector<long long> a(n);
    vector<pair<long long, long long>> v;
    ans.clear();
    used = vector<long long>(n);
    g = vector<vector<long long>>(n, vector<long long>(n));
    for (i = 0; i < n; i++) cin >> a[i];
    for (i = 0; i < n; i++)
      for (j = 0; j < n; j++)
        if (a[i] != a[j]) g[i][j] = 1;
    dfs(0);
    for (i = 0; i < n; i++)
      if (!used[i]) t = 0;
    if (!t)
      cout << "NO\n";
    else {
      cout << "YES\n";
      for (i = 0; i < n - 1; i++)
        cout << ans[i].first << ' ' << ans[i].second << '\n';
    }
  }
}

```


### Prompt

Your challenge is to write a cpp solution to the following problem:

This is the hard version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved.

Pikachu is a cute and friendly pokémon living in the wild pikachu herd.

But it has become known recently that infamous team R wanted to steal all these pokémon! Pokémon trainer Andrew decided to help Pikachu to build a pokémon army to resist.

First, Andrew counted all the pokémon — there were exactly n pikachu. The strength of the i-th pokémon is equal to a_i, and all these numbers are distinct.

As an army, Andrew can choose any non-empty subsequence of pokemons. In other words, Andrew chooses some array b from k indices such that 1 ≤ b_1 < b_2 < ... < b_k ≤ n, and his army will consist of pokémons with forces a_{b_1}, a_{b_2}, ..., a_{b_k}.

The strength of the army is equal to the alternating sum of elements of the subsequence; that is, a_{b_1} - a_{b_2} + a_{b_3} - a_{b_4} + ....

Andrew is experimenting with pokémon order. He performs q operations. In i-th operation Andrew swaps l_i-th and r_i-th pokémon.

Andrew wants to know the maximal stregth of the army he can achieve with the initial pokémon placement. He also needs to know the maximal strength after each operation.

Help Andrew and the pokémon, or team R will realize their tricky plan!

Input

Each test contains multiple test cases.

The first line contains one positive integer t (1 ≤ t ≤ 10^3) denoting the number of test cases. Description of the test cases follows.

The first line of each test case contains two integers n and q (1 ≤ n ≤ 3 ⋅ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) denoting the number of pokémon and number of operations respectively.

The second line contains n distinct positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) denoting the strengths of the pokémon.

i-th of the last q lines contains two positive integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ n) denoting the indices of pokémon that were swapped in the i-th operation.

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

Output

For each test case, print q+1 integers: the maximal strength of army before the swaps and after each swap.

Example

Input

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

Output

3
4
2
2
2
9
10
10
10
9
11

Note

Let's look at the third test case:

Initially we can build an army in such way: [1 2 5 4 3 6 7], its strength will be 5-3+7=9.

After first operation we can build an army in such way: [2 1 5 4 3 6 7], its strength will be 2-1+5-3+7=10.

After second operation we can build an army in such way: [2 1 5 4 3 7 6], its strength will be 2-1+5-3+7=10.

After third operation we can build an army in such way: [2 1 4 5 3 7 6], its strength will be 2-1+5-3+7=10.

After forth operation we can build an army in such way: [1 2 4 5 3 7 6], its strength will be 5-3+7=9.

After all operations we can build an army in such way: [1 4 2 5 3 7 6], its strength will be 4-2+5-3+7=11.

### Response

```cpp
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
const long INF = LONG_LONG_MAX, MOD = 1e9 + 7;
using namespace std;
template <typename Arg1>
void __f(const char *name, Arg1 &&arg1) {
  cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char *names, Arg1 &&arg1, Args &&...args) {
  const char *comma = strchr(names + 1, ',');
  cout.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
void solve() {
  long long n, i, j, q, mx = 0;
  cin >> n >> q;
  long long a[n], dp[n][2];
  for (int i = 0; i < n; ++i) cin >> a[i];
  mx = a[0];
  for (i = 1; i < n; ++i) mx += max(a[i] - a[i - 1], 0LL);
  cout << mx << '\n';
  for (i = 0; i < q; i++) {
    long long x, y, t;
    cin >> x >> y;
    --x;
    --y;
    t = a[x];
    if ((x != 0) && a[x] - a[x - 1] > 0) mx -= a[x] - a[x - 1];
    if (x != n - 1) mx -= max(0LL, a[x + 1] - a[x]);
    if (x == 0) mx -= a[0], mx += a[y];
    a[x] = a[y];
    if (x != n - 1) mx += max(a[x + 1] - a[x], 0LL);
    if (x != 0) {
      mx += max(0LL, a[x] - a[x - 1]);
    }
    x = y;
    if ((x != 0) && a[x] - a[x - 1] > 0) mx -= a[x] - a[x - 1];
    if (x != n - 1) mx -= max(0LL, a[x + 1] - a[x]);
    if (x == 0) mx -= a[0], mx += t;
    a[x] = t;
    if (x != n - 1) mx += max(a[x + 1] - a[x], 0LL);
    if (x != 0) {
      mx += max(0LL, a[x] - a[x - 1]);
    }
    cout << mx << '\n';
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cout << fixed << setprecision(11);
  long long t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}

```


### Prompt

Develop a solution in cpp to the problem described below:

The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer.

This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is ti + k degrees.

Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.

To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.

Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.

Input

The first input line contains two integers n and m (1 ≤ n ≤ 105; 1 ≤ m ≤ 106) — the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1 ≤ ti, Ti, xi, costi ≤ 106). The numbers in the lines are separated by single spaces.

Output

Print the only integer — the minimum number of roubles the organizers will have to spend to transport all schoolchildren.

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

Examples

Input

2 10
30 35 1 100
20 35 10 10

Output

120

Input

3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000

Output

200065

Note

In the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30 + 10 = 40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100 + 10 + 10 = 120 rubles.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  long long ans = 0;
  for (int i = (0); i < (n); ++i) {
    long long t, T, x, cost;
    cin >> t >> T >> x >> cost;
    if (t >= T) {
      ans += cost + m * x;
      continue;
    }
    long long aux1 = cost;
    if (m > (T - t)) aux1 += m * x;
    long long aux2 = (long long)ceil((double)(m - (T - t)) / (T - t)) + 1;
    aux2 *= cost;
    ans += min(aux1, aux2);
  }
  cout << ans << endl;
  return 0;
}

```


### Prompt

Create a solution in cpp for the following problem:

There are N cities numbered 1 to N, connected by M railroads.

You are now at City 1, with 10^{100} gold coins and S silver coins in your pocket.

The i-th railroad connects City U_i and City V_i bidirectionally, and a one-way trip costs A_i silver coins and takes B_i minutes. You cannot use gold coins to pay the fare.

There is an exchange counter in each city. At the exchange counter in City i, you can get C_i silver coins for 1 gold coin. The transaction takes D_i minutes for each gold coin you give. You can exchange any number of gold coins at each exchange counter.

For each t=2, ..., N, find the minimum time needed to travel from City 1 to City t. You can ignore the time spent waiting for trains.

Constraints

* 2 \leq N \leq 50
* N-1 \leq M \leq 100
* 0 \leq S \leq 10^9
* 1 \leq A_i \leq 50
* 1 \leq B_i,C_i,D_i \leq 10^9
* 1 \leq U_i < V_i \leq N
* There is no pair i, j(i \neq j) such that (U_i,V_i)=(U_j,V_j).
* Each city t=2,...,N can be reached from City 1 with some number of railroads.
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M S
U_1 V_1 A_1 B_1
:
U_M V_M A_M B_M
C_1 D_1
:
C_N D_N

Output

For each t=2, ..., N in this order, print a line containing the minimum time needed to travel from City 1 to City t.

Examples

Input

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

Output

2
14

Input

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

Output

5
5
7

Input

6 5 1
1 2 1 1
1 3 2 1
2 4 5 1
3 5 11 1
1 6 50 1
1 10000
1 3000
1 700
1 100
1 1
100 1

Output

1
9003
14606
16510
16576

Input

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

Output

1
3
5

Input

2 1 0
1 2 1 1
1 1000000000
1 1

Output

1000000001

### Response

```cpp
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=59,M=109;
struct edge{int to,nxt,a,w;}e[M*2]; int hd[N],tot;
void add(int u,int v,int a,int w){e[++tot]=(edge){v,hd[u],a,w};hd[u]=tot;}
int n,m,s; int maxs; int c[N],d[N]; int dis[N][N*N],ans[N];
struct node{
	int u,sil,f;
	bool operator < (const node b)const{return f>b.f;}
	bool operator > (const node b)const{return f<b.f;}
};
void dijkstra(){
	memset(dis,0x3f,sizeof(dis)); memset(ans,0x3f,sizeof(ans));
	priority_queue<node>q; q.push((node){1,s}); dis[1][s]=0;
	while(!q.empty()){
		int u=q.top().u,sil=q.top().sil; q.pop();
		ans[u]=min(ans[u],dis[u][sil]);
		for(int i=hd[u],v;i;i=e[i].nxt){
			if(e[i].a<=sil&&dis[v=e[i].to][sil-e[i].a]>dis[u][sil]+e[i].w)
				q.push((node){v,sil-e[i].a,dis[v][sil-e[i].a]=dis[u][sil]+e[i].w});
		}
		if(sil<maxs&&dis[u][min(sil+c[u],maxs)]>dis[u][sil]+d[u])
			q.push((node){u,min(maxs,sil+c[u]),dis[u][min(sil+c[u],maxs)]=dis[u][sil]+d[u]});
	}
}
signed main(){
	scanf("%lld%lld%lld",&n,&m,&s);
	for(int i=1,u,v,a,w;i<=m;i++)
		scanf("%lld%lld%lld%lld",&u,&v,&a,&w),add(u,v,a,w),add(v,u,a,w),maxs+=a;
	s=min(s,maxs);
	for(int i=1;i<=n;i++)
		scanf("%lld%lld",&c[i],&d[i]);
	dijkstra();
	for(int i=2;i<=n;i++) printf("%lld\n",ans[i]);
	return 0;
}
```


### Prompt

Create a solution in CPP for the following problem:

A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time li and the finish time ri (li ≤ ri).

Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?

No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.

Input

The first line contains integer number n (1 ≤ n ≤ 5·105) — number of orders. The following n lines contain integer values li and ri each (1 ≤ li ≤ ri ≤ 109).

Output

Print the maximal number of orders that can be accepted.

Examples

Input

2
7 11
4 7

Output

1

Input

5
1 2
2 3
3 4
4 5
5 6

Output

3

Input

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

Output

2

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int n, ans = 1;
pair<int, int> p[500000];
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> p[i].second >> p[i].first;
  }
  sort(p, p + n);
  int r = p[0].first;
  for (int i = 1; i < n; i++) {
    if (p[i].second > r) {
      ans++;
      r = p[i].first;
    }
  }
  cout << ans << endl;
  return 0;
}

```


### Prompt

Construct a CPP code solution to the problem outlined:

We have N balls. The i-th ball has an integer A_i written on it.
For each k=1, 2, ..., N, solve the following problem and print the answer.

* Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

* 3 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq N
* All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Examples

Input

5
1 1 2 1 2

Output

2
2
3
2
3

Input

4
1 2 3 4

Output

0
0
0
0

Input

5
3 3 3 3 3

Output

6
6
6
6
6

Input

8
1 2 1 4 2 1 4 1

Output

5
7
5
7
7
5
7
5

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;

int main()
{
  int n;
  cin >> n;

  vector<int> a(n);
  for (auto&& e : a)
    cin >> e;

  vector<int64_t> c(n + 1);
  for (const auto& e : a)
    c[e]++;

  int64_t ans = 0;
  for (const auto& e : c)
    ans += e * (e - 1) / 2;

  for (const auto& e : a)
    cout << ans - (c[e] - 1) << endl;
}

```


### Prompt

Please formulate a Cpp solution to the following problem:

You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.

You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.

You are given a sequence of hits, the i-th hit deals a_i units of damage to the opponent's character. To perform the i-th hit you have to press the button s_i on your gamepad. Hits are numbered from 1 to n.

You know that if you press some button more than k times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.

To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of a_i over all i for the hits which weren't skipped.

Note that if you skip the hit then the counter of consecutive presses the button won't reset.

Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.

Input

The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of hits and the maximum number of times you can push the same button in a row.

The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the damage of the i-th hit.

The third line of the input contains the string s consisting of exactly n lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).

Output

Print one integer dmg — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.

Examples

Input

7 3
1 5 16 18 7 2 10
baaaaca

Output

54

Input

5 5
2 4 1 3 1000
aaaaa

Output

1010

Input

5 4
2 4 1 3 1000
aaaaa

Output

1009

Input

8 1
10 15 2 1 4 8 15 16
qqwweerr

Output

41

Input

6 3
14 18 9 19 2 15
cccccc

Output

52

Input

2 1
10 10
qq

Output

10

Note

In the first example you can choose hits with numbers [1, 3, 4, 5, 6, 7] with the total damage 1 + 16 + 18 + 7 + 2 + 10 = 54.

In the second example you can choose all hits so the total damage is 2 + 4 + 1 + 3 + 1000 = 1010.

In the third example you can choose all hits expect the third one so the total damage is 2 + 4 + 3 + 1000 = 1009.

In the fourth example you can choose hits with numbers [2, 3, 6, 8]. Only this way you can reach the maximum total damage 15 + 2 + 8 + 16 = 41.

In the fifth example you can choose only hits with numbers [2, 4, 6] with the total damage 18 + 19 + 15 = 52.

In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage 10.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const long long INF = 2e18;
void print(int a[], int n) {
  for (int i = 0; i < n; i++) cout << a[i] << " ";
  cout << "\n";
}
void printll(long long a[], long long n) {
  for (int i = 0; i < n; i++) cout << a[i] << " ";
  cout << "\n";
}
void _print(long long t) { cerr << t; }
void _print(int t) { cerr << t; }
void _print(string t) { cerr << t; }
void _print(char t) { cerr << t; }
void _print(double t) { cerr << t; }
void _print(unsigned long long t) { cerr << t; }
template <class T, class V>
void _print(pair<T, V> p);
template <class T>
void _print(vector<T> v);
template <class T>
void _print(set<T> v);
template <class T, class V>
void _print(map<T, V> v);
template <class T>
void _print(multiset<T> v);
template <class T, class V>
void _print(pair<T, V> p) {
  cerr << "{";
  _print(p.first);
  cerr << ",";
  _print(p.second);
  cerr << "}";
}
template <class T>
void _print(vector<T> v) {
  cerr << "[ ";
  for (T i : v) {
    _print(i);
    cerr << " ";
  }
  cerr << "]";
}
template <class T>
void _print(set<T> v) {
  cerr << "[ ";
  for (T i : v) {
    _print(i);
    cerr << " ";
  }
  cerr << "]";
}
template <class T>
void _print(multiset<T> v) {
  cerr << "[ ";
  for (T i : v) {
    _print(i);
    cerr << " ";
  }
  cerr << "]";
}
template <class T, class V>
void _print(map<T, V> v) {
  cerr << "[ ";
  for (auto i : v) {
    _print(i);
    cerr << " ";
  }
  cerr << "]";
}
vector<int> primes;
void sieve() {
  bool isPrime[10000 + 5];
  memset(isPrime, true, sizeof(isPrime));
  for (int i = 3; i * i <= 10000 + 5; i += 2) {
    if (isPrime[i]) {
      for (int j = i * i; j <= 10000 + 5; j += 2 * i) {
        isPrime[j] = false;
      }
    }
  }
  primes.push_back(2);
  for (int i = 3; i < 10000 + 5; i += 2) {
    if (isPrime[i]) primes.push_back(i);
  }
}
vector<long long> findPrimeFactors(long long n) {
  vector<long long> primeFactors;
  while (n % 2 == 0) primeFactors.push_back(2), n = n / 2;
  for (long long i = 3; i * i <= n; i = i + 2) {
    while (n % i == 0) {
      primeFactors.push_back(i);
      n = n / i;
    }
  }
  if (n > 2) primeFactors.push_back(n);
  return primeFactors;
}
vector<long long> allDivisiors(long long n) {
  vector<long long> divisors;
  long long limit = sqrt(n + 1);
  for (long long i = 1; i <= limit; i++) {
    if (n % i == 0) {
      if (n / i == i)
        divisors.push_back(i);
      else
        divisors.push_back(i), divisors.push_back(n / i);
    }
  }
  return divisors;
}
bool isPrime(long long n) {
  if (n == 2 or n == 3) return true;
  if (n % 2 == 0) return false;
  for (long long i = 3; i * i <= n; i += 2)
    if (n % i == 0) return false;
  return true;
}
long long nsum(long long n) { return (n * (n + 1)) / 2; }
long long power(long long n, long long p) {
  if (p == 0) return 1;
  if (p == 1) return n;
  long long ans = 1;
  while (p) {
    if (p & 1) ans = ans * n;
    n = n * n;
    p = p / 2;
  }
  return ans;
}
long long mpower(long long n, long long p, long long mod) {
  if (p == -1) p = mod - 2;
  if (p == 0) return 1;
  if (p == 1) return n;
  long long ans = 1;
  while (p) {
    if (p & 1) ans = (ans * n) % mod;
    n = (n * n) % mod;
    p = p / 2;
  }
  return ans;
}
bool isPalindrome(string s) {
  int N = s.size();
  for (int i = 0; i < (N / 2); i++) {
    if (s[i] != s[N - 1 - i]) return 0;
  }
  return 1;
}
long long mod = 1e9 + 7;
void solve() {
  long long n;
  cin >> n;
  long long k;
  cin >> k;
  long long a[n];
  for (int i = 0; i < (n); i++) cin >> a[i];
  string s;
  cin >> s;
  long long mx = 2e5 + 5;
  vector<vector<long long>> v(mx);
  v[0].push_back(a[0]);
  long long j = 0;
  for (int i = 1; i <= (n - 1); i++) {
    if (s[i] == s[i - 1]) {
      v[j].push_back(a[i]);
    } else {
      j++;
      v[j].push_back(a[i]);
    }
  }
  long long sum = 0;
  for (int i = 0; i < (mx); i++) {
    long long x = v[i].size();
    if (x == 0) break;
    sort(v[i].begin(), v[i].end(), greater<int>());
    x = min(k, x);
    for (int j = 0; j < (x); j++) {
      sum += v[i][j];
    }
  }
  cout << sum << "\n";
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int tc = 1;
  for (int i = 1; i <= tc; i++) {
    solve();
  }
}

```


### Prompt

Generate a Cpp solution to the following problem:

This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following:

  * he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, …, a_r out, removing the rest of the array.
  * he then cuts this range into multiple subranges.
  * to add a number theory spice to it, he requires that the elements of every subrange must have their product equal to their [least common multiple (LCM)](https://en.wikipedia.org/wiki/Least_common_multiple).

Formally, he partitions the elements of a_l, a_{l + 1}, …, a_r into contiguous subarrays such that the product of every subarray is equal to its LCM. Now, for q independent ranges (l, r), tell Baby Ehab the minimum number of subarrays he needs.

Input

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

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

Each of the next q lines contains 2 integers l and r (1 ≤ l ≤ r ≤ n) — the endpoints of this query's interval.

Output

For each query, print its answer on a new line.

Example

Input

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

Output

3
1
2

Note

The first query asks about the whole array. You can partition it into [2], [3,10,7], and [5,14]. The first subrange has product and LCM equal to 2. The second has product and LCM equal to 210. And the third has product and LCM equal to 70. Another possible partitioning is [2,3], [10,7], and [5,14].

The second query asks about the range (2,4). Its product is equal to its LCM, so you don't need to partition it further.

The last query asks about the range (3,5). You can partition it into [10,7] and [5].

### Response

```cpp
 #include<bits/stdc++.h>
using namespace std;

typedef long long ll;
const ll N = 100001;

#define maxINF 1e18
#define minINF 1e-18
#define FASTIO ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define pri(a,s,n) for(int i = s; i < n; i++) cout<<a[i]<<" "; cout << endl
int main()
{
    FASTIO;
    int t = 1; //cin >> t;
    int sieve[N] = {0};
    for(int i = 2; i < N; i++){
        if(sieve[i] == 0){
            for(int j = 1; j*i < N; j++) sieve[j*i] = i;
        }
    }
    sieve[1] = 1;
    for(int qw = 1; qw <= t; qw++){
        int n,q; cin >> n >> q;
        vector<int> a(n),last(n),primes(N,0);
        vector<vector<int>> pr(n);
        for(int i = 0; i < n; i++){
            cin >> a[i];
            int s = sieve[a[i]], o = a[i];
            pr[i].push_back(s);
            while(o != 1){
                if(sieve[o] != s){
                    s = sieve[o];
                    pr[i].push_back(s);
                }
                o /= s;
            }
        }
        int l = 0, r = 1;
        for(int i = 0; i < pr[l].size(); i++) primes[pr[l][i]] = 1;
        while(r < n){
            int i;
            if(a[r] == 1){r++; continue;}
            for(i = 0; i < pr[r].size(); i++){
                if(primes[pr[r][i]] == 1){
                    last[l] = r-1;
                    for(int i = 0; i < pr[l].size(); i++) primes[pr[l][i]] = 0;
                    l++;
                    i--;
                }
                else primes[pr[r][i]] = 1;
            }
            r++;
        }
        while(l < n){
            last[l] = r-1; l++;
        }

        //pri(last,0,n);
        vector<vector<ll>> dp(n);
        for(int i = 0; (1<<i) <= n; i++){
            for(int j = 0; j < n; j++){

                if(i == 0) dp[j].push_back(last[j]);
                else if(dp[j][dp[j].size()-1] == n-1) continue;
                else if(dp[dp[j][dp[j].size()-1]+1].size() < i) continue;
                else dp[j].push_back(dp[dp[j][dp[j].size()-1]+1][i-1]);
                //if(i > 0) cout<<i<<" "<<j<<" "<<dp[j][dp[j].size()-1] <<" "<< dp[dp[j][dp[j].size()-1]+1][i-1] << endl;
            }
        }
//        for(int i = 0; i < n; i++){
//            for(int j = 0; j < dp[i].size(); j++) cout << dp[i][j]<<" ";
//            cout << endl;
//        }
//        q=0;
        while(q--){
            cin >> l >> r;
            int c = 0,i = 0,p=1;
            l--;r--;
            while(dp[l][0] < r){
                //cout<<l<<" "<<i<<" "<<dp[l][i]<<" ";
                if(dp[l].size() > i && dp[l][i] < r) {i++;}
                else if(dp[l].size() > i && dp[l][i] == r) {c += (1<<i);p=0; break;}
                else {c += (1<<(i-1)); l = dp[l][i-1]+1; i = 0;}
                //cout << c << endl;
            }

            cout << c + p << endl;
        }
    }
}
/*10 6
1 1 1 1 3 1 1 6 1 1*/

```


### Prompt

Your task is to create a CPP solution to the following problem:

Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.

In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.

He thinks that each student will take place equal to <image>. In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position.

GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.

Input

The first line contains integer n (1 ≤ n ≤ 2000), number of GukiZ's students.

The second line contains n numbers a1, a2, ... an (1 ≤ ai ≤ 2000) where ai is the rating of i-th student (1 ≤ i ≤ n).

Output

In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.

Examples

Input

3
1 3 3

Output

3 1 1

Input

1
1

Output

1

Input

5
3 5 3 4 5

Output

4 1 4 3 1

Note

In the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.

In the second sample, first student is the only one on the contest.

In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  int n;
  cin >> n;
  vector<pair<int, int> > A;
  for (int i = 0; i < n; ++i) {
    int x;
    cin >> x;
    A.push_back(make_pair(x, i));
  }
  sort(A.rbegin(), A.rend());
  int ans[n];
  ans[A[0].second] = 1;
  for (int i = 1; i < A.size(); ++i) {
    if (A[i].first == A[i - 1].first)
      ans[A[i].second] = ans[A[i - 1].second];
    else
      ans[A[i].second] = i + 1;
  }
  for (int i = 0; i < n; ++i) {
    cout << ans[i] << " ";
  }
  return 0;
}

```


### Prompt

Please create a solution in Cpp to the following problem:

Problem statement

There is a town with a size of H in the north-south direction and W in the east-west direction. In the town, square plots with a side length of 1 are maintained without gaps, and one house is built in each plot.

A typhoon broke out over a section of the town, causing damage and then changing to an extratropical cyclone over a section. No damage is done after the change. As shown in the figure below, a typhoon is a square with a height of 3 and a width of 3, and the square with a star is called the center. The typhoon moves to the vicinity of 8 in units of sections. In other words, the center of the typhoon moves with the whole so that it moves to the section that shares the sides or vertices (including the current section). However, the typhoon does not protrude outside the town, and the center of the typhoon is the 0th and H-1st sections from the north and the 0th and W-1st sections from the west, as shown in the shaded area in the figure below. Move so that it does not pass.

<image>

Once a typhoon hits the sky, the degree of damage to the house changes as follows.

> No damage → Partially damaged → Half destroyed → Completely destroyed → No trace

Fortunately, however, there seems to be no house that has become a trace pear. Since the damage situation of each house is given, find the point where the typhoon occurred and the point where it changed to an extratropical cyclone. However, if the generated section is s_ith from the north, s_jth from the west, and the section changed to an extratropical cyclone is t_ith from the north and t_jth from the west, the two points are 10000 t_i + t_j ≤ 10000 s_i + s_j. Determined to meet.

input

H \ W
D_ {11} \… \ D_ {1W}
D_ {21} \… \ D_ {2W}
...
D_ {H1} \… \ D_ {HW}

D_ {ij} is an integer that expresses the degree of damage to the i-th house from the north and the j-th house from the west as follows.

* 0: No damage
* 1: Partially damaged
* 2: Half destroyed
* 3: Completely destroyed

Constraint

* An integer
* Input is given only if the answer is uniquely determined
* 3 ≤ H, W ≤ 500
* 0 ≤ D_ {ij} ≤ 3

output

Output the answer in one line as follows.

s_i \ s_j \ t_i \ t_j

sample

Sample input 1

7 5
0 0 0 0 0
0 1 1 1 0
0 2 2 2 0
0 3 3 3 0
0 2 2 2 0
0 1 1 1 0
0 0 0 0 0

Sample output 1

4 2 2 2

Sample input 2

6 6
0 0 0 1 1 1
0 0 0 2 2 2
0 0 1 3 3 2
1 2 3 3 2 1
1 2 3 2 1 0
1 2 2 1 0 0

Sample output 2

4 1 1 4

Sample input 3

4 4
2 2 2 0
2 2 2 0
2 2 2 0
0 0 0 0

Sample output 3

1 1 1 1

Example

Input

7 5
0 0 0 0 0
0 1 1 1 0
0 2 2 2 0
0 3 3 3 0
0 2 2 2 0
0 1 1 1 0
0 0 0 0 0

Output

4 2 2 2

### Response

```cpp
#include "bits/stdc++.h"
using namespace std;

//#define int long long
#define DEBUG 0
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(a) (a).begin(),(a).end()
#define dump(o) if(DEBUG){cerr<<#o<<" "<<o<<endl;}
#define dumpc(o) if(DEBUG){cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;}
using ll = long long; using ull = unsigned long long; using pii = pair<int, int>;
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
static const int MOD = 1e9 + 7;

#if DEBUG
const int MAX = 10;
#else
const int MAX = 510;
#endif

int D[MAX][MAX] = {};
int H, W;

bool A[MAX][MAX] = {};

signed main() {
	cin >> H >> W;
	rep(i, 0, H)rep(j, 0, W) {
		cin >> D[i][j];
	}
	rep(i, 0, H)rep(j, 0, W) {
		if (D[i][j]) {
			A[i + 1][j + 1] = true;
			int d = D[i][j];
			rep(ii, i, i + 3)rep(jj, j, j + 3) {
				D[ii][jj] -= d;
			}
		}
	}
	rep(i, 0, H)dumpc(A[i]);
	vector<pii> v;
	rep(i, 0, H)rep(j, 0, W) {
		if (!A[i][j])continue;
		int cnt = 0;
		rep(ii, i - 1, i + 2)rep(jj, j - 1, j + 2) {
			if (A[ii][jj])cnt++;
		}
		if (cnt == 2)v.emplace_back(pii(i, j));
		if (cnt == 1) {
			v.emplace_back(pii(i, j));
			v.emplace_back(pii(i, j));
		}
	}
	dump(v.size());
	sort(all(v));
	cout << v[1].first << " " << v[1].second << " " << v[0].first << " " << v[0].second << endl;
	return 0;
}
```


### Prompt

Develop a solution in Cpp to the problem described below:

For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:

* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.

Constraints

* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge

Input

|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).

Output

Print the shortest distance in a line. If there is no solution, print -1.

Examples

Input

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

Output

16

Input

3 3
0 1 1
1 2 1
0 2 1

Output

-1

### Response

```cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int INF = 100000;

const int MAX_V = 15;
int d[MAX_V][MAX_V];
int V;

int dp[1 << MAX_V][MAX_V];

int solve(int S, int v)
{
  if(dp[S][v] >= 0) return dp[S][v];

  if(S == (1 << V) - 1 && v == 0) return dp[S][v] = 0;

  int ans = INF;
  for(int u = 0; u < V; u++)
    if(!(S >> u & 1))
      ans = min(ans, solve(S | 1 << u, u) + d[v][u]);

  return dp[S][v] = ans;
}

int main()
{
  int E;
  scanf("%d %d", &V, &E);

  fill(&d[0][0], &d[MAX_V][0], INF);
  for(int i = 0; i < E; i++){
    int s, t, c;
    scanf("%d %d %d", &s, &t, &c);
    d[s][t] = c;
  }

  fill(&dp[0][0], &dp[1 << MAX_V][0], -1);
  int ans = solve(0, 0);
  if(ans != INF)
    printf("%d\n", ans);
  else
    printf("-1\n");
}
```


### Prompt

Your challenge is to write a CPP solution to the following problem:

Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.

Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.

Input

The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).

Output

Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.

If there are multiple suitable tables, you are allowed to print any of them.

Examples

Input

2 4

Output

1 3
3 1

Input

4 7

Output

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

Note

In the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.

In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
long long int gcd(long long int a, long long int b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
int main() {
  long long int n, k, i, j;
  cin >> n >> k;
  for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
      if (i == j)
        cout << k << " ";
      else
        cout << "0 ";
    }
    cout << endl;
  }
  return 0;
}

```


### Prompt

Your task is to create a CPP solution to the following problem:

You are given an undirected graph with N vertices and M edges. Here, N-1≤M≤N holds and the graph is connected. There are no self-loops or multiple edges in this graph.

The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices a_i and b_i.

The color of each vertex can be either white or black. Initially, all the vertices are white. Snuke is trying to turn all the vertices black by performing the following operation some number of times:

* Select a pair of adjacent vertices with the same color, and invert the colors of those vertices. That is, if the vertices are both white, then turn them black, and vice versa.

Determine if it is possible to turn all the vertices black. If the answer is positive, find the minimum number of times the operation needs to be performed in order to achieve the objective.

Constraints

* 2≤N≤10^5
* N-1≤M≤N
* 1≤a_i,b_i≤N
* There are no self-loops or multiple edges in the given graph.
* The given graph is connected.

Input

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

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

If it is possible to turn all the vertices black, print the minimum number of times the operation needs to be performed in order to achieve the objective. Otherwise, print `-1` instead.

Examples

Input

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

Output

5

Input

3 2
1 2
2 3

Output

-1

Input

4 4
1 2
2 3
3 4
4 1

Output

2

Input

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

Output

7

### Response

```cpp
#include <bits/stdc++.h>
#define N 100005
#define ll long long
#define NoSolution return puts("-1"),0
#define For(i,x,y) for(int i=(x);i<=(y);++i)
#define Rof(i,x,y) for(int i=(x);i>=(y);--i)
#define Edge(x) for(int i=head[x];i;i=e[i].nxt)
#define mset(x,y) memset(x,y,sizeof(x))
#define p_b push_back
using namespace std;

int f[N],fa[N],dep[N],cnt=0,b[N],_u,_v;
vector<int> g[N];

void dfs(int x,int v){
	f[x]=v;
	for(auto to:g[x]){
		if(!dep[to]){
			fa[to]=x,dep[to]=dep[x]+1;
			dfs(to,-v);
			f[x]+=f[to];
		} else if(to!=fa[x]){
			_u=x,_v=to;
		}
	}
}
int main(){
	int n,m,u,v,ans=INT_MAX,mid,tmp,cnt;
	dep[1]=1;
	scanf("%d%d",&n,&m);
	For(i,1,m){
		scanf("%d%d",&u,&v);
		g[u].p_b(v),g[v].p_b(u);
	}
	dfs(1,1);
	if(m==n-1){
		ans=0;
		if(f[1]) NoSolution;
		For(i,1,n) ans+=abs(f[i]);
		printf("%d\n",ans);
	} else{
		if((dep[_v]-dep[_u]+1)%2==0){
			if(f[1]) NoSolution;
			tmp=0,cnt=0;
			For(i,1,n) tmp+=abs(f[i]);
			ans=min(ans,tmp);
			for(int i=_v;i!=_u;i=fa[i]) tmp-=abs(f[i]),b[++cnt]=f[i];
			sort(b+1,b+cnt+1);
			cnt&1?mid=b[(cnt+1)/2]:mid=(b[cnt/2]+b[cnt/2+1])/2;
			tmp+=abs(mid);
			for(int i=_v;i!=_u;i=fa[i]) tmp+=abs(f[i]-mid);
			ans=min(ans,tmp);
			printf("%d\n",ans);
		} else{
			if(f[1]%2) NoSolution;
			int tmp=f[1]/2;ans=abs(tmp);
			for(int i=_u;i;i=fa[i]) f[i]-=tmp;
			for(int i=_v;i;i=fa[i]) f[i]-=tmp;
			For(i,1,n) ans+=abs(f[i]);
			printf("%d\n",ans);
		}
	}
}
```


### Prompt

Please provide a CPP coded solution to the problem described below:

Diameter of a Tree

Given a tree T with non-negative weight, find the diameter of the tree.

The diameter of a tree is the maximum distance between two nodes in a tree.

Constraints

* 1 ≤ n ≤ 100,000
* 0 ≤ wi ≤ 1,000

Input

n
s1 t1 w1
s2 t2 w2
:
sn-1 tn-1 wn-1

The first line consists of an integer n which represents the number of nodes in the tree. Every node has a unique ID from 0 to n-1 respectively.

In the following n-1 lines, edges of the tree are given. si and ti represent end-points of the i-th edge (undirected) and wi represents the weight (distance) of the i-th edge.

Output

Print the diameter of the tree in a line.

Examples

Input

4
0 1 2
1 2 1
1 3 3

Output

5

Input

4
0 1 1
1 2 2
2 3 4

Output

7

### Response

```cpp
#include<bits/stdc++.h>
using namespace std;

const int SIZE = 100001;
vector<pair<int, int>> A[SIZE];
int max_distance = 0, farthest;
bool color[SIZE];
void dfs(int x = 0, int dist = 0){
    color[x] = true;
    for (int i = 0; i < A[x].size(); i++){
        if (max_distance < dist){
            farthest = x;
            max_distance = dist;
        }
        if (color[A[x][i].first]) continue;
        dfs(A[x][i].first, dist + A[x][i].second);
    }
}

int main(){
    int n, s, t, w;
    cin >> n;
    for (int i = 1; i < n; i++){
        cin >> s >> t >> w;
        A[s].push_back(make_pair(t, w));
        A[t].push_back(make_pair(s, w));
    }
    dfs();
    for (int i = 0; i < SIZE; i++)color[i] = false;
    dfs(farthest);
    cout << max_distance << endl;
}

```


### Prompt

Your challenge is to write a cpp solution to the following problem:

Input

The input contains two integers a1, a2 (0 ≤ ai ≤ 109), separated by a single space.

Output

Output a single integer.

Examples

Input

3 14

Output

44

Input

27 12

Output

48

Input

100 200

Output

102

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b;
  string s1, s2;
  cin >> a >> s1;
  for (int i = 0; i <= (int)s1.length() - 1; i++) {
    s2 = s1[i] + s2;
  }
  sscanf(s2.c_str(), "%d", &b);
  cout << a + b << endl;
}

```


### Prompt

In cpp, your task is to solve the following problem:

There are N people numbered 1 to N. Each person wears a red hat or a blue hat.

You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

* 1 \leq N \leq 100
* |s| = N
* s_i is `R` or `B`.

Input

Input is given from Standard Input in the following format:

N
s

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print `Yes`; otherwise, print `No`.

Examples

Input

4
RRBR

Output

Yes

Input

4
BRBR

Output

No

### Response

```cpp
#include <bits/stdc++.h>

int main() {

    int N; std::cin >> N;
    std::string s; std::cin >> s;
    int r = std::count(s.begin(), s.end(), 'R');
    std::cout << ((r + r > s.length()) ? "Yes" : "No") << std::endl;
}
```


### Prompt

Generate a cpp solution to the following problem:

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

* All values in input are integers.
* 2 \leq A \leq 20
* 1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Examples

Input

4 10

Output

3

Input

8 9

Output

2

Input

8 8

Output

1

### Response

```cpp
#include<stdio.h>
int main()
{
    int A,B;
    scanf("%d%d",&A,&B);
    printf("%d\n",(A+B-3)/(A-1));
    return 0;
}

```


### Prompt

Create a solution in CPP for the following problem:

You have r red and b blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:

  * has at least one red bean (or the number of red beans r_i ≥ 1);
  * has at least one blue bean (or the number of blue beans b_i ≥ 1);
  * the number of red and blue beans should differ in no more than d (or |r_i - b_i| ≤ d)

Can you distribute all beans?

Input

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

The first and only line of each test case contains three integers r, b, and d (1 ≤ r, b ≤ 10^9; 0 ≤ d ≤ 10^9) — the number of red and blue beans and the maximum absolute difference in each packet.

Output

For each test case, if you can distribute all beans, print YES. Otherwise, print NO.

You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

Example

Input

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

Output

YES
YES
NO
NO

Note

In the first test case, you can form one packet with 1 red and 1 blue bean. The absolute difference |1 - 1| = 0 ≤ d.

In the second test case, you can form two packets: 1 red and 4 blue beans in the first packet and 1 red and 3 blue beans in the second one.

In the third test case, since b = 1, you can form only one packet with 6 red and 1 blue beans. The absolute difference |6 - 1| = 5 > d.

In the fourth test case, since d = 0 so each packet should contain the same number of red and blue beans, but r ≠ b.

### Response

```cpp
#include<bits/stdc++.h>
using namespace std;
int main()
{
	long long int n,r,b,d,minn=0,maxn;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		cin>>r>>b>>d;
		if(abs(r-b)>d)
		{
			minn=min(r,b);
			maxn=abs(r-b)/minn;
			if(maxn>d)
			{
				printf("NO\n");
			}
			if(maxn==d)
			{
				if(abs(r-b)%minn==0)
				{
					printf("YES\n");
				}
				else
				{
					printf("NO\n");
				}
			}
			if(maxn<d)
			{
				printf("YES\n");
			}
		}
		else
		{
			printf("YES\n");
		}
	}
	return 0;
}

```


### Prompt

Generate a cpp solution to the following problem:

You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.

Calculate the minimum weight among all triangulations of the polygon.

Input

The first line contains single integer n (3 ≤ n ≤ 500) — the number of vertices in the regular polygon.

Output

Print one integer — the minimum weight among all triangulations of the given polygon.

Examples

Input

3

Output

6

Input

4

Output

18

Note

According to Wiki: polygon triangulation is the decomposition of a polygonal area (simple polygon) P into a set of triangles, i. e., finding a set of triangles with pairwise non-intersecting interiors whose union is P.

In the first example the polygon is a triangle, so we don't need to cut it further, so the answer is 1 ⋅ 2 ⋅ 3 = 6.

In the second example the polygon is a rectangle, so it should be divided into two triangles. It's optimal to cut it using diagonal 1-3 so answer is 1 ⋅ 2 ⋅ 3 + 1 ⋅ 3 ⋅ 4 = 6 + 12 = 18.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  int minCost = 0;
  for (int i = 1; i < n - 1; i++) {
    minCost += 1 * (i + 1) * (i + 2);
  }
  cout << minCost << endl;
  return 0;
}

```


### Prompt

Develop a solution in CPP to the problem described below:

"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.

The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below.

<image> The left light ray passes through a regular column, and the right ray — through the magic column.

The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position.

<image> This figure illustrates the first sample test.

Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.

Input

The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.

Output

Print the minimum number of columns to make magic or -1 if it's impossible to do.

Examples

Input

3 3
.#.
...
.#.

Output

2

Input

4 3
##.
...
.#.
.#.

Output

2

Note

The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3 + 10;
int n, m, d[maxn][maxn], val[maxn][maxn];
string s[maxn];
vector<int> rows[maxn], cols[maxn];
bool marked[maxn][maxn];
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    cin >> s[i];
    for (int j = 0; j < m; j++) {
      if (s[i][j] == '#') {
        rows[i].push_back(j);
        cols[j].push_back(i);
      }
    }
  }
  queue<pair<int, int>> q;
  q.push(make_pair(n - 1, m));
  val[n - 1][m] = 1;
  while (!q.empty()) {
    auto v = q.front();
    q.pop();
    if (val[v.first][v.second]) {
      for (int c : rows[v.first]) {
        if (!marked[v.first][c]) {
          d[v.first][c] = d[v.first][v.second] + 1;
          q.push(make_pair(v.first, c));
          marked[v.first][c] = true;
          val[v.first][c] = 0;
        }
      }
    } else {
      for (int r : cols[v.second]) {
        if (!marked[r][v.second]) {
          d[r][v.second] = d[v.first][v.second] + 1;
          q.push(make_pair(r, v.second));
          marked[r][v.second] = true;
          val[r][v.second] = 1;
        }
      }
    }
  }
  int ans = 1e9;
  for (int i = 0; i < m; i++) {
    if (s[0][i] == '#' && marked[0][i]) ans = min(ans, d[0][i]);
  }
  if (ans == 1e9)
    cout << -1 << endl;
  else
    cout << ans << endl;
  return 0;
}

```


### Prompt

Develop a solution in CPP to the problem described below:

Princess Heidi decided to give orders to all her K Rebel ship commanders in person. Unfortunately, she is currently travelling through hyperspace, and will leave it only at N specific moments t1, t2, ..., tN. The meetings with commanders must therefore start and stop at those times. Namely, each commander will board her ship at some time ti and disembark at some later time tj. Of course, Heidi needs to meet with all commanders, and no two meetings can be held during the same time. Two commanders cannot even meet at the beginnings/endings of the hyperspace jumps, because too many ships in one position could give out their coordinates to the enemy.

Your task is to find minimum time that Princess Heidi has to spend on meetings, with her schedule satisfying the conditions above.

Input

The first line contains two integers K, N (2 ≤ 2K ≤ N ≤ 500000, K ≤ 5000). The second line contains N distinct integers t1, t2, ..., tN (1 ≤ ti ≤ 109) representing the times when Heidi leaves hyperspace.

Output

Output only one integer: the minimum time spent on meetings.

Examples

Input

2 5
1 4 6 7 12

Output

4

Input

3 6
6 3 4 2 5 1

Output

3

Input

4 12
15 7 4 19 3 30 14 1 5 23 17 25

Output

6

Note

In the first example, there are five valid schedules: [1, 4], [6, 7] with total time 4, [1, 4], [6, 12] with total time 9, [1, 4], [7, 12] with total time 8, [1, 6], [7, 12] with total time 10, and [4, 6], [7, 12] with total time 7. So the answer is 4.

In the second example, there is only 1 valid schedule: [1, 2], [3, 4], [5, 6].

For the third example, one possible schedule with total time 6 is: [1, 3], [4, 5], [14, 15], [23, 25].

### Response

```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 7;
const int K = 5e3 + 3;
const int INF = 4e9;
int k, n;
int t[N], a[N];
vector<pair<int, int> > z;
vector<int> id;
int dp[2][K][2];
void minimize(int &x, int y) {
  if (y < x) x = y;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> k >> n;
  for (int i = 1; i <= n; ++i) cin >> t[i];
  sort(t + 1, t + n + 1);
  for (int i = 1; i <= n - 1; ++i) z.push_back(make_pair(t[i + 1] - t[i], i));
  sort(z.begin(), z.end());
  for (int i = 0; i < min((int)z.size(), k << 2); ++i) {
    id.push_back(z[i].second);
    id.push_back(z[i].second + 1);
  }
  sort(id.begin(), id.end());
  id.erase(unique(id.begin(), id.end()), id.end());
  sort(id.begin(), id.end());
  id.resize(unique(id.begin(), id.end()) - id.begin());
  n = 0;
  for (int i = 0; i < id.size(); ++i) a[++n] = t[id[i]];
  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j <= min(n >> 1, k); ++j) {
      for (int last = 0; last < 2; ++last) {
        dp[i][j][last] = INF;
      }
    }
  }
  dp[0][0][0] = 0;
  for (int i = 2; i <= n; ++i) {
    for (int j = 0; j <= min(i >> 1, k); ++j) {
      for (int last = 0; last < 2; ++last) {
        if (dp[0][j][last] == INF) {
          continue;
        }
        for (int chosen = 0; chosen < 2; ++chosen) {
          if (last && chosen) continue;
          minimize(dp[1][j + chosen][chosen],
                   dp[0][j][last] + (chosen ? (a[i] - a[i - 1]) : 0));
        }
      }
    }
    for (int j = 0; j <= min(i >> 1, k); ++j)
      for (int last = 0; last < 2; ++last) {
        dp[0][j][last] = dp[1][j][last];
        dp[1][j][last] = INF;
      }
  }
  cout << min(dp[0][k][0], dp[0][k][1]) << endl;
}

```


### Prompt

Your challenge is to write a Cpp solution to the following problem:

Given the string S and m queries. The i-th query is given by the two strings xi and yi.

For each query, answer the longest substring of the string S, starting with xi and ending with yi.

For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character string S means that a certain integer i exists and Tj = Si + j is satisfied for 1 ≤ j ≤ | T |. Where Tj represents the jth character of T.

Constraints

* 1 ≤ | S | ≤ 2 x 105
* 1 ≤ m ≤ 105
* 1 ≤ | xi |, | yi |
* $ \ sum ^ m_ {i = 1} $ (| xi | + | yi |) ≤ 2 x 105
* S and xi, yi consist only of half-width lowercase letters.

Input

The input is given in the following format.

S
m
x1 y1
x2 y2
::
xm ym

* The character string S is given on the first line.
* The number of queries m is given in the second line.
* Of the m lines from the 3rd line, the i-th query string xi, yi is given on the i-th line, separated by spaces.

Output

Answer the maximum substring length in the following format.

len1
len2
::
lenm

Output the longest substring length leni that satisfies the condition for the i-th query on the i-th line of the m lines from the first line. If there is no such substring, output 0.

Examples

Input

abracadabra
5
ab a
a a
b c
ac ca
z z

Output

11
11
4
3
0

Input

howistheprogress
4
ist prog
s ss
how is
the progress

Output

9
12
5
11

Input

icpcsummertraining
9
mm m
icpc summer
train ing
summer mm
i c
i i
g g
train i
summer er

Output

2
10
8
0
4
16
1
6
6

### Response

```cpp
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <cassert>

using namespace std;
using ll = long long;

class SuffixArray
{
public:
    SuffixArray(const string& s) : s{s}, index1{static_cast<int>(s.size())}, suffix_array(index1 + 1), rank(index1 + 1), lcp(index1 + 1), buf(index1 + 1)
    {
        for (int i = 0; i <= index1; i++) {
            suffix_array[i] = i;
            rank[i] = i < index1 ? s[i] : -1;
        }
        auto comp = [&](const int i, const int j) {
            if (rank[i] != rank[j]) {
                return rank[i] < rank[j];
            } else {
                const int ri = (i + index2 <= index1) ? rank[i + index2] : -1;
                const int rj = (j + index2 <= index1) ? rank[j + index2] : -1;
                return ri < rj;
            }
        };
        for (index2 = 1; index2 <= index1; index2 *= 2) {
            sort(suffix_array.begin(), suffix_array.end(), comp);
            buf[suffix_array[0]] = 0;
            for (int i = 1; i <= index1; i++) {
                buf[suffix_array[i]] = buf[suffix_array[i - 1]] + (comp(suffix_array[i - 1], suffix_array[i]) ? 1 : 0);
            }
            for (int i = 0; i <= index1; i++) {
                rank[i] = buf[i];
            }
        }

        for (int i = 0; i <= index1; i++) {
            rank[suffix_array[i]] = i;
        }
        int h = 0;
        lcp[0] = 0;
        for (int i = 0; i < index1; i++) {
            {
                const int j = suffix_array[rank[i] - 1];
                if (h > 0) {
                    h--;
                }
                for (; j + h < index1 and i + h < index1; h++) {
                    if (s[j + h] != s[i + h]) {
                        break;
                    }
                }
                lcp[rank[i] - 1] = h;
            }
        }
    }
    bool contain(const string& t) const
    {
        int a = 0;
        int b = s.size();
        while (b - a > 1) {
            const int c = (a + b) / 2;
            if (s.compare(suffix_array[c], t.size(), t) < 0) {
                a = c;
            } else {
                b = c;
            }
        }
        return s.compare(suffix_array[b], t.size(), t) == 0;
    }

    int lower_bound(const string& suffix) const
    {
        int a = 0;
        int b = s.size() + 1;
        while (b - a > 1) {
            const int c = (a + b) / 2;
            if (s.compare(suffix_array[c], string::npos, suffix) < 0) {
                a = c;
            } else {
                b = c;
            }
        }
        return b;
    }

    int upper_bound(const string& suffix) const
    {
        int a = 0;
        int b = s.size() + 1;
        while (b - a > 1) {
            const int c = (a + b) / 2;
            if (s.compare(suffix_array[c], suffix.size(), suffix) <= 0) {
                a = c;
            } else {
                b = c;
            }
        }
        return b;
    }

    const vector<int>& getArray() const
    {
        return suffix_array;
    }

private:
    const string s;
    const int index1;
    int index2;
    vector<int> suffix_array;
    vector<int> rank;
    vector<int> lcp;
    vector<int> buf;
};

template <typename Base>
class SparseTable
{
public:
    using T = typename Base::T;
    using SemiLattice = Base;
    SparseTable(const vector<T>& val) : size(val.size()), lg2(size + 1, 0)
    {
        for (int i = 2; i <= size; i++) {
            lg2[i] = lg2[i / 2] + 1;
        }
        table.resize(size, vector<T>(lg2[size] + 1));
        for (int i = 0; i < size; i++) {
            table[i][0] = val[i];
        }
        for (int j = 0; j < lg2[size]; j++) {
            const int w = 1 << j;
            for (int i = 0; i <= size - (w << 1); i++) {
                T tl = table[i][j], tr = table[i + w][j];
                table[i][j + 1] = op(tl, tr);
            }
        }
    }

    T accumulate(const int l, const int r) const
    {
        assert(0 <= l and l < r and r <= size);
        const int j = lg2[r - l];
        return op(table[l][j], table[r - (1 << j)][j]);
    }

private:
    const int size;
    vector<int> lg2;
    vector<vector<T>> table;
    const SemiLattice op{};
};

struct Min {
    using T = int;
    T operator()(const T& a, const T& b) const
    {
        return min(a, b);
    }
};
struct Max {
    using T = int;
    T operator()(const T& a, const T& b) const
    {
        return max(a, b);
    }
};

int main()
{
    string s;
    cin >> s;
    SuffixArray sa(s);
    // for (const int i : sa.getArray()) {
    //     cerr << s.substr(i, s.size() - i) << endl;
    // }
    SparseTable<Min> stmin{sa.getArray()};
    SparseTable<Max> stmax{sa.getArray()};

    int m;
    cin >> m;
    for (int i = 0; i < m; i++) {
        string x, y;
        cin >> x >> y;
        const int xl = sa.lower_bound(x);
        const int xr = sa.upper_bound(x);
        const int yl = sa.lower_bound(y);
        const int yr = sa.upper_bound(y);
        if (xl < xr and yl < yr) {
            const int lower = stmin.accumulate(xl, xr);
            const int upper = stmax.accumulate(yl, yr);
            if (lower + x.size() <= upper + y.size()) {
                cout << upper - lower + y.size() << endl;
            } else {
                cout << 0 << endl;
            }
        } else {
            cout << 0 << endl;
        }
    }
    return 0;
}
```