Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l).Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≤ i ≤ j ≤ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.

The first line contains four positive space-separated integers n, l, x, y (2 ≤ n ≤ 105, 2 ≤ l ≤ 109, 1 ≤ x < y ≤ l) — the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin.

In the first line print a single non-negative integer v — the minimum number of marks that you need to add on the ruler. In the second line print v space-separated integers p1, p2, ..., pv (0 ≤ pi ≤ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.

NoteIn the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills.

var nums = readline().split(' ');
var n = parseInt(nums[0]);
var l = parseInt(nums[1]);
var x = parseInt(nums[2]);
var y = parseInt(nums[3]);
var a = readline().split(' ');
for(var i=0;i<a.length;i++)
{
    a[i]=parseInt(a[i]);
}

var fx = false;
var fy = false;

fx= findVal(x);
fy= findVal(y);

if(fx==true&&fy==true)
{
    print(0);
}
else if(fx==true)
{
    print(1);
	print(y);
}
else if(fy==true)
{
    print(1);
	print(x);
}
else
{
    var ans = -1;
    for(var i=0;i<n;i++)
	{
	    if(a[i]-x>0)
		{
		    var t = a[i]-x;
			if(hasVal(t-y)||hasVal(t+y))
			{
			    ans = a[i]-x;
				break;
			}
		}
		if(a[i]+x<l)
		{
		    var t = a[i]+x;
			if(hasVal(t-y)||hasVal(t+y))
			{
			    ans = a[i]+x;
				break;
			}
		}
	}

	if(ans!=-1)
	{
	    print(1);
		print(ans);
	}
	else
	{
	    print(2);
		print(x+' '+y);
	}
}

function findVal( val )
{
    var st = 0;
	for(var i=1;i<n;i++)
	{
		if(a[i]-a[st]==val)
		{
		    return true;
		}
		else if(a[i]-a[st]<val)
		{
		    continue;
		}
		else
		{
		    while(a[i]-a[st]>val)
			{
			    st++;
			}
			if(a[i]-a[st]==val)
			{
			    return true;
			}
		}
	}
	return false;
}

function hasVal(val)
{
    var st = 0;
	var ed = n-1;
	if(val==a[st]||val==a[ed])
	{
	    return true;
	}
	if(val<0||val>l)
	{
	    return false;
	}
	while(ed-st>1)
	{
	    var mid = ((st+ed)>>1);
		if(a[mid]==val)
		{
		    return true;
		}
		if(a[mid]>val)
		{
		    ed=mid;
	    }
		else
		{
		    st=mid;
		}
	}
	return false;
}

var nums = readline().split(' ');
var n = parseInt(nums[0]);
var l = parseInt(nums[1]);
var x = parseInt(nums[2]);
var y = parseInt(nums[3]);
var a = readline().split(' ');

var fx = false;
var fy = false;

fx= findVal(x);
fy= findVal(y);

if(fx==true&&fy==true)
{
    print(0);
}
else if(fx==true)
{
    print(1);
	print(y);
}
else if(fy==true)
{
    print(1);
	print(x);
}
else
{
    var ans = -1;
    for(var i=0;i<n;i++)
	{
	    if(a[i]-x>0)
		{
		    var t = a[i]-x;
			if(hasVal(t-y)||hasVal(t+y))
			{
			    ans = a[i]-x;
				break;
			}
		}
		if(a[i]+x<l)
		{
		    var t = a[i]+x;
			if(hasVal(t-y)||hasVal(t+y))
			{
			    ans = a[i]+x;
				break;
			}
		}
	}

	if(ans!=-1)
	{
	    print(1);
		print(ans);
	}
	else
	{
	    print(2);
		print(x+' '+y);
	}
}

function findVal( val )
{
    var st = 0;
	for(var i=1;i<n;i++)
	{
		if(a[i]-a[st]==val)
		{
		    return true;
		}
		else if(a[i]-a[st]<val)
		{
		    continue;
		}
		else
		{
		    while(a[i]-a[st]>val)
			{
			    st++;
			}
			if(a[i]-a[st]==val)
			{
			    return true;
			}
		}
	}
	return false;
}

function hasVal(val)
{
    var st = 0;
	var ed = n-1;
	if(val==a[st]||val==a[ed])
	{
	    return true;
	}
	if(val<0||val>l)
	{
	    return false;
	}
	while(ed-st>1)
	{
	    var mid = ((st+ed)>>1);
		if(a[mid]==val)
		{
		    return true;
		}
		if(a[mid]>val)
		{
		    ed=mid;
	    }
		else
		{
		    st=mid;
		}
	}
	return false;
}


You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.You have to determine the length of the longest balanced substring of s.

The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

NoteIn the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.In the second example it's impossible to find a non-empty balanced substring.

function main() {
  var n = +next();
  var s = next();
  var t = {0: -1};
  var sum = 0;
  var ans = 0;
  for (var i = -1; ++ i < n; ) {
    sum += s[i] === '1' ? 1 : -1;
    if (t[sum] != null) {
      ans = Math.max(ans, i - t[sum]);
    } else t[sum] = i;
  }
  print(ans);
}

var line = null, linepos = 0;
function next() {
  if (!line || linepos === line.length) {
    line = readline().split(' ');
    linepos = 0;
  }
  return line[linepos++];
}

if (typeof readline == 'undefined') {
  process.stdin.resume();
  process.stdin.setEncoding('ascii');

  var input_stdin = "";
  process.stdin.on('data', function (data) { input_stdin += data; });
  process.stdin.on('end', function () {
    // input_stdin = input_stdin.split(/\s/);
    input_stdin = input_stdin.split('\n');
    var curline = 0;
    readline = () => input_stdin[curline++];
    if (typeof print === 'undefined') print = console.log;
    main();
  });
} else main();


You are given a permutation $$$a_1,a_2,\ldots,a_n$$$ of integers from $$$0$$$ to $$$n - 1$$$. Your task is to find how many permutations $$$b_1,b_2,\ldots,b_n$$$ are similar to permutation $$$a$$$. Two permutations $$$a$$$ and $$$b$$$ of size $$$n$$$ are considered similar if for all intervals $$$[l,r]$$$ ($$$1 \le l \le r \le n$$$), the following condition is satisfied: $$$$$$\operatorname{MEX}([a_l,a_{l+1},\ldots,a_r])=\operatorname{MEX}([b_l,b_{l+1},\ldots,b_r]),$$$$$$ where the $$$\operatorname{MEX}$$$ of a collection of integers $$$c_1,c_2,\ldots,c_k$$$ is defined as the smallest non-negative integer $$$x$$$ which does not occur in collection $$$c$$$. For example, $$$\operatorname{MEX}([1,2,3,4,5])=0$$$, and $$$\operatorname{MEX}([0,1,2,4,5])=3$$$.Since the total number of such permutations can be very large, you will have to print its remainder modulo $$$10^9+7$$$.In this problem, a permutation of size $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n-1$$$ in arbitrary order. For example, $$$[1,0,2,4,3]$$$ is a permutation, while $$$[0,1,1]$$$ is not, since $$$1$$$ appears twice in the array. $$$[0,1,3]$$$ is also not a permutation, since $$$n=3$$$ and there is a $$$3$$$ in the array.

Each test contains multiple test cases. The first line of input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of permutation $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0 \le a_i \lt n$$$) — the elements of permutation $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer, the number of permutations similar to permutation $$$a$$$, taken modulo $$$10^9+7$$$.

NoteFor the first test case, the only permutations similar to $$$a=[4,0,3,2,1]$$$ are $$$[4,0,3,2,1]$$$ and $$$[4,0,2,3,1]$$$.For the second and third test cases, the given permutations are only similar to themselves.For the fourth test case, there are $$$4$$$ permutations similar to $$$a=[1,2,4,0,5,3]$$$:   $$$[1,2,4,0,5,3]$$$;  $$$[1,2,5,0,4,3]$$$;  $$$[1,4,2,0,5,3]$$$;  $$$[1,5,2,0,4,3]$$$.

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();
    let mod = 10 ** 9 + 7;

    for (let test = 0; test < N; test++) {
        let size = Number(readline());
        let arr = readline().split(' ').map(Number);
        let pos = {};
        arr.forEach((num, i) => pos[num] = i);

        let result = 1;
        let left = pos[0] > pos[1] ? pos[1] : pos[0];
        let right = pos[0] > pos[1] ? pos[0] : pos[1];
        for (let i = 2; i < size; i++) {
            if (pos[i] > left && pos[i] < right) {
                result *= right - left + 1 - i;
            } else if (pos[i] < left) {
                left = pos[i];
            } else if (pos[i] > right) {
                right = pos[i];
            }
            result = result % mod;
        }

        output(result);
    }
}

'use strict';

function solve(n, a) {
  const l = new Array(n),
        r = new Array(n);
  const f = [1, 1];
  for (let i = 2; i < n; i++) f[i] = f[i - 1] * i;
  const segTree = new SegTree(n);
  let stack = [];
  for (let i = 0; i < n; i++) {
    if (!stack.length || a[stack[stack.length - 1]] > a[i]) {
      stack.push(i);
      l[i] = i;
    } else {
      const left = binarySearch(stack, 0, stack.length - 1, j => a[stack[j]] > a[i]);
      l[i] = stack[left];
    }
  }
  stack = [];
  for (let i = n - 1; i >= 0; i--) {
    if (!stack.length || a[stack[stack.length - 1]] > a[i]) {
      stack.push(i);
      r[i] = i;
    } else {
      const right = binarySearch(stack, 0, stack.length - 1, j => a[stack[j]] > a[i]);
      r[i] = stack[right];
    }
  }
  const indexs = [];
  for (let i = 0; i < n; i++) {
    if (l[i] === i || r[i] === i) segTree.update(i, i, 1);else indexs.push(i);
  }
  indexs.sort((x, y) => a[x] - a[y]);
  let res = 1;
  for (let i of indexs) {
    const left = l[i] + 1,
          right = r[i] - 1;
    res = mul(res, right - left + 1 - segTree.query(left, right));
    segTree.update(i, i, 1);
  }
  return res;
}
function binarySearch(arr, l, r, comp) {
  while (l < r) {
    const m = l + r >> 1;
    if (comp(m)) l = m + 1;else r = m;
  }
  return l;
}
const MOD = 10 ** 9 + 7;
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}
class SegTree {
  constructor(n) {
    this.n = n;
    this.root = this._newNode();
    this.update = (x, y, z) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      this._update(this.root, 0, n, x, y, z);
    };
    this.query = (x, y) => {
      x = Math.max(x, 0);
      y = Math.min(y, n);
      return this._query(this.root, 0, n, x, y);
    };
  }
  _newNode(val = 0, left = null, right = null) {
    return {
      val,
      left,
      right,
      add: 0
    };
  }
  _down(node, l, r) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    const mid = Math.floor((l + r) / 2);
    left.add += node.add;
    left.val += node.add * (mid - l + 1);
    right.add += node.add;
    right.val += node.add * (r - mid);
    node.add = 0;
  }
  _up(node) {
    const {
      left,
      right
    } = node;
    if (!left || !right) return;
    node.val = left.val + right.val;
  }
  _update(node, l, r, x, y, z) {
    if (!node) return;
    if (l === x && r === y) {
      node.add += z;
      node.val += z * (r - l + 1);
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) this._update(node.left, l, mid, x, y, z);else if (x > mid) this._update(node.right, mid + 1, r, x, y, z);else this._update(node.left, l, mid, x, mid, z), this._update(node.right, mid + 1, r, mid + 1, y, z);
    this._up(node);
  }
  _query(node, l, r, x, y) {
    if (y < x) return 0;
    if (!node) return 0;
    if (l === x && r === y) return node.val;
    let res = 0,
        mid = Math.floor((l + r) / 2);
    if (!node.left) {
      node.left = this._newNode();
      node.right = this._newNode();
    }
    this._down(node, l, r);
    if (y <= mid) res = this._query(node.left, l, mid, x, y);else if (x > mid) res = this._query(node.right, mid + 1, r, x, y);else res = this._query(node.left, l, mid, x, mid) + this._query(node.right, mid + 1, r, mid + 1, y);
    this._up(node);
    return res;
  }
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});

'use strict';

function solve(n, a) {
  const l = new Array(n),
        r = new Array(n);
  const f = [1, 1];
  for (let i = 2; i < n; i++) f[i] = f[i - 1] * i;
  let stack = [];
  for (let i = 0; i < n; i++) {
    if (!stack.length || a[stack[stack.length - 1]] > a[i]) {
      stack.push(i);
      l[i] = i;
    } else {
      const left = binarySearch(stack, 0, stack.length - 1, j => a[stack[j]] > a[i]);
      l[i] = stack[left];
    }
  }
  stack = [];
  for (let i = n - 1; i >= 0; i--) {
    if (!stack.length || a[stack[stack.length - 1]] > a[i]) {
      stack.push(i);
      r[i] = i;
    } else {
      const right = binarySearch(stack, 0, stack.length - 1, j => a[stack[j]] > a[i]);
      r[i] = stack[right];
    }
  }
  const sum = [];
  for (let i = 0; i < n; i++) {
    var _sum;
    sum[i] = (_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0;
    if (l[i] === i || r[i] === i) sum[i]++;
  }
  let res = 1,
      pre = -1;
  for (let i = 0, j = 0; i < n; i = ++j) {
    if (l[i] === i || r[i] === i) continue;
    const arr = [i];
    while (j + 1 < n && r[j + 1] !== j + 1 && l[j + 1] !== j + 1) {
      j++;
      arr.push(j);
    }
    arr.sort((x, y) => a[x] - a[y]);
    pre = i - 1;
    for (let k of arr) {
      res = mul(res, r[k] - pre - 1 - (sum[r[k] - 1] - sum[pre]));
      pre++;
    }
  }
  return res;
}
function binarySearch(arr, l, r, comp) {
  while (l < r) {
    const m = l + r >> 1;
    if (comp(m)) l = m + 1;else r = m;
  }
  return l;
}
const MOD = 10 ** 9 + 7;
function mul(...args) {
  if (args.length === 0) throw new Error('参数不能为空');
  if (args.length === 1) return args[0];
  const [a, b] = args;
  if (args.length > 2) return mul(mul(a, b), ...args.slice(2));
  return (Math.floor(a / 65536) * b % MOD * 65536 + (a & 65535) * b) % MOD;
}

async function main(read) {
  try {
    let t = Number(await read());
    let res = new Array(t);
    for (let i = 0; i < t; i++) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res[i] = solve(n, a);
    }
    return res.join('\n');
  } catch (error) {
    console.log(error);
  }
}

let inputs,
    str = '';
function read() {
  return inputs.next().value.trim();
}
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', input => str += input);
process.stdin.on('end', async () => {
  inputs = str.split('\n').values();
  const output = await main(read);
  process.stdout.write(output);
});


At the big break Nastya came to the school dining room. There are $$$n$$$ pupils in the school, numbered from $$$1$$$ to $$$n$$$. Unfortunately, Nastya came pretty late, so that all pupils had already stood in the queue, i.e. Nastya took the last place in the queue. Of course, it's a little bit sad for Nastya, but she is not going to despond because some pupils in the queue can agree to change places with some other pupils.Formally, there are some pairs $$$u$$$, $$$v$$$ such that if the pupil with number $$$u$$$ stands directly in front of the pupil with number $$$v$$$, Nastya can ask them and they will change places. Nastya asks you to find the maximal number of places in queue she can move forward.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 3 \cdot 10^{5}$$$, $$$0 \leq m \leq 5 \cdot 10^{5}$$$) — the number of pupils in the queue and number of pairs of pupils such that the first one agrees to change places with the second one if the first is directly in front of the second. The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — the initial arrangement of pupils in the queue, from the queue start to its end ($$$1 \leq p_i \leq n$$$, $$$p$$$ is a permutation of integers from $$$1$$$ to $$$n$$$). In other words, $$$p_i$$$ is the number of the pupil who stands on the $$$i$$$-th position in the queue. The $$$i$$$-th of the following $$$m$$$ lines contains two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), denoting that the pupil with number $$$u_i$$$ agrees to change places with the pupil with number $$$v_i$$$ if $$$u_i$$$ is directly in front of $$$v_i$$$. It is guaranteed that if $$$i \neq j$$$, than $$$v_i \neq v_j$$$ or $$$u_i \neq u_j$$$. Note that it is possible that in some pairs both pupils agree to change places with each other. Nastya is the last person in the queue, i.e. the pupil with number $$$p_n$$$.

Print a single integer — the number of places in queue she can move forward.

NoteIn the first example Nastya can just change places with the first pupil in the queue.Optimal sequence of changes in the second example is   change places for pupils with numbers $$$1$$$ and $$$3$$$.  change places for pupils with numbers $$$3$$$ and $$$2$$$.  change places for pupils with numbers $$$1$$$ and $$$2$$$. The queue looks like $$$[3, 1, 2]$$$, then $$$[1, 3, 2]$$$, then $$$[1, 2, 3]$$$, and finally $$$[2, 1, 3]$$$ after these operations.

const nm = readline().split(" ").map(e => parseInt(e));
const n = nm[0];
const m = nm[1];

const p = readline().split(" ").map(e => parseInt(e));
const my = p[n - 1];

const add = (x, y) => {
    if (g[x] === undefined) {
        g[x] = [];
    }
    g[x].push(y);
};
const g = [];
for (var i = 0; i < m; i++) {
    var xy = readline().split(" ").map(e => parseInt(e));
    var x = xy[0];
    var y = xy[1];
    add(y, x);
}

const left = [];
for (var i = 1; i <= n; i++) {
    left[i] = n;
}
if (g[my] !== undefined) {
    for (var i of g[my]) {
        left[i] = n - 1;
    }
}

var result = 0;
var last = n - 1;
for (var i = n - 2; i >= 0; i--) {
    if (left[p[i]] == last) {
        result++;
    } else {
        if (g[p[i]] !== undefined) {
            for (var j of g[p[i]]) {
                if (left[j] == last) {
                    left[j] = i;
                }
            }
        }
        last = i;
    }
}
print(result);

const nm = readline().split(" ").map(e => parseInt(e));
const n = nm[0];
const m = nm[1];

const p = readline().split(" ").map(e => parseInt(e));
const my = p[n - 1];

const add = (x, y) => {
    if (g[x] === undefined) {
        g[x] = [];
    }
    g[x].push(y);
};
const g = [];
for (var i = 0; i < m; i++) {
    var xy = readline().split(" ").map(e => parseInt(e));
    var x = xy[0];
    var y = xy[1];
    add(x, y);
    add(y, x);
}

const left = [];
for (var i = 1; i <= n; i++) {
    left[i] = n;
}
if (g[my] !== undefined) {
    for (var i of g[my]) {
        left[i] = n - 1;
    }
}

var result = 0;
for (var i = n - 2; i >= 0; i--) {
    if (left[p[i]] == i + 1) {
        result++;
    }
    if (g[p[i]] !== undefined) {
        for (var j of g[p[i]]) {
            left[j] = i;
        }
    }
}
print(result);

const nm = readline().split(" ").map(e => parseInt(e));
const n = nm[0];
const m = nm[1];

const p = readline().split(" ").map(e => parseInt(e));
const my = p[n - 1];

const add = (x, y) => {
    if (g[x] === undefined) {
        g[x] = [];
    }
    g[x].push(y);
};
const g = [];
for (var i = 0; i < m; i++) {
    var xy = readline().split(" ").map(e => parseInt(e));
    var x = xy[0];
    var y = xy[1];
    add(x, y);
    add(y, x);
}

var possible = new Set();
if (g[my] !== undefined) {
    for (var i of g[my]) {
        possible.add(i);
    }
}

var result = 0;
for (var i = n - 2; i >= 0; i--) {
    if (possible.has(p[i])) {
        result++;
        possible.delete(p[i]);
    }
    var newPossible = new Set();
    if (g[p[i]] !== undefined) {
        for (var j of g[p[i]]) {
            if (possible.has(j)) {
                newPossible.add(j);
            }
        }
    }
    possible = newPossible;
}
print(result);

const nm = readline().split(" ").map(e => parseInt(e));
const n = nm[0];
const m = nm[1];

const p = readline().split(" ").map(e => parseInt(e));
const my = p[n - 1];

const add = (x, y) => {
    if (g[x] === undefined) {
        g[x] = [];
    }
    g[x].push(y);
};
const g = [];
for (var i = 0; i < m; i++) {
    var xy = readline().split(" ").map(e => parseInt(e));
    var x = xy[0];
    var y = xy[1];
    add(y, x);
}

const left = [];
for (var i = 1; i <= n; i++) {
    left[i] = n;
}
if (g[my] !== undefined) {
    for (var i of g[my]) {
        left[i] = n - 1;
    }
}

var result = 0;
for (var i = n - 2; i >= 0; i--) {
    if (left[p[i]] == i + 1) {
        result++;
    }
    if (g[p[i]] !== undefined) {
        for (var j of g[p[i]]) {
            if (left[j] == i + 1) {
               left[j]--;
            }
        }
    }
}
print(result);

const nm = readline().split(" ").map(e => parseInt(e));
const n = nm[0];
const m = nm[1];

const p = readline().split(" ").map(e => parseInt(e));
const my = p[n - 1];

const add = (x, y) => {
    if (g[x] === undefined) {
        g[x] = [];
    }
    g[x].push(y);
};
const g = [];
for (var i = 0; i < m; i++) {
    var xy = readline().split(" ").map(e => parseInt(e));
    var x = xy[0];
    var y = xy[1];
    add(x, y);
    add(y, x);
}

var possible = new Set();
if (g[my] !== undefined) {
    for (var i of g[my]) {
        possible.add(i);
    }
}

var result = 0;
for (var i = n - 2; i >= 0; i--) {
    if (possible.has(p[i])) {
        result++;
        possible.delete(p[i]);
    }
    const newPossible = new Set();
    if (g[p[i]] !== undefined) {
        for (var j of g[p[i]]) {
            if (possible.has(j)) {
                newPossible.add(j);
            }
        }
    }
    possible = newPossible;
}
print(result);

const nm = readline().split(" ").map(e => parseInt(e));
const n = nm[0];
const m = nm[1];

const p = readline().split(" ").map(e => parseInt(e));
const my = p[n - 1];

const add = (x, y) => {
    if (g[x] === undefined) {
        g[x] = [];
    }
    g[x].push(y);
};
const g = [];
for (var i = 0; i < m; i++) {
    var xy = readline().split(" ").map(e => parseInt(e));
    var x = xy[0];
    var y = xy[1];
    add(y, x);
}

const left = [];
for (var i = 1; i <= n; i++) {
    left[i] = n;
}
if (g[my] !== undefined) {
    for (var i of g[my]) {
        left[i] = n - 1;
    }
}

var result = 0;
for (var i = n - 2; i >= 0; i--) {
    if (left[p[i]] == i + 1) {
        result++;
    }
    if (g[p[i]] !== undefined) {
        for (var j of g[p[i]]) {
            left[j] = i;
        }
    }
}
print(result);


Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell $$$(x,y)$$$ of an infinite grid. According to Alice's theory, cat needs to move:   exactly $$$a$$$ steps left: from $$$(u,v)$$$ to $$$(u-1,v)$$$;  exactly $$$b$$$ steps right: from $$$(u,v)$$$ to $$$(u+1,v)$$$;  exactly $$$c$$$ steps down: from $$$(u,v)$$$ to $$$(u,v-1)$$$;  exactly $$$d$$$ steps up: from $$$(u,v)$$$ to $$$(u,v+1)$$$. Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $$$1$$$ step left, $$$3$$$ steps right and $$$2$$$ steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $$$[x_1,x_2]\times [y_1,y_2]$$$, i.e. for every cat's position $$$(u,v)$$$ of a walk $$$x_1 \le u \le x_2$$$ and $$$y_1 \le v \le y_2$$$ holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly $$$a+b+c+d$$$ unit moves ($$$a$$$ to the left, $$$b$$$ to the right, $$$c$$$ to the down, $$$d$$$ to the up). Alice can do the moves in any order. Her current position $$$(u, v)$$$ should always satisfy the constraints: $$$x_1 \le u \le x_2$$$, $$$y_1 \le v \le y_2$$$. The staring point is $$$(x, y)$$$.You are required to answer $$$t$$$ test cases independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases.  The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,b,c,d \le 10^8$$$, $$$a+b+c+d \ge 1$$$). The second line of the test case contains six integers $$$x$$$, $$$y$$$, $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$-10^8 \le x_1\le x \le x_2 \le 10^8$$$, $$$-10^8 \le y_1 \le y \le y_2 \le 10^8$$$).

For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line.  You can print each letter in any case (upper or lower).

NoteIn the first test case, one valid exercising walk is $$$$$$(0,0)\rightarrow (-1,0) \rightarrow (-2,0)\rightarrow (-2,1) \rightarrow (-2,2)\rightarrow (-1,2)\rightarrow(0,2)\rightarrow (0,1)\rightarrow (0,0) \rightarrow (-1,0)$$$$$$

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var one = nextIntArray();
        var a = one[0];
        var b = one[1];
        var c = one[2];
        var d = one[3];
        var two = nextIntArray();
        var x = two[0];
        var y = two[1];
        var x1 = two[2];
        var y1 = two[3];
        var x2 = two[4];
        var y2 = two[5];
        if((x1 == x2 && (a > 0 || b > 0)) || (y1 == y2 && (c > 0 || d > 0))){
          output[i] = "NO";
        }else{
          var diffX = x + (b - a);
          var diffY = y + (d - c);
          if(diffX >= x1 && diffX <= x2 && diffY >= y1 && diffY <= y2){
            output[i] = "YES";
          }else{
            output[i] = "NO";
          }
        }
    }
    myout(myconv(output,9));
}

process.stdin.resume()
process.stdin.setEncoding('utf-8')

let input = ''
let ptr = 0
process.stdin.on('data', (i) => {
  input += i
})

process.stdin.on('end', () => {
  input = input.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))
  main()
})

function wr(...x) {
  console.log(...x)
}

function sort(a, inc = true) {
  if (inc) a.sort((a, b) => a - b)
  else a.sort((a, b) => b - a)
}

function readInt() {
  return parseInt(input[ptr++])
}

function readString() {
  return input[ptr++]
}

function readStrings() {
  return input[ptr++].split(' ')
}

function readInts() {
  return input[ptr++].split(' ').map(a => parseInt(a))
}

function main() {
  let t = readInt()
  while (t--) {
    const [a, b, c, d] = readInts()
    let [x, y, x1, y1, x2, y2] = readInts()
    if (a > 0 && b > 0 && x - 1 < x1 && x + 1 > x2) {
      wr('NO')
      continue
    }
    if (c > 0 && d > 0 && y - 1 < y1 && y + 1 > y2) {
      wr('NO')
      continue
    }
    let left = 0
    let right = 0
    let up = 0
    let down = 0
    if (a > b) left = a - b
    if (b > a) right = b - a
    if (c > d) down = c - d
    if (d > c) up = d - c
    if (left > 0) x -= left
    if (right > 0) x += right
    if (up > 0) y += up
    if (down > 0) y -= down
    if (x1 <= x && x <= x2 && y1 <= y && y <= y2) wr('YES')
    else wr('NO')
  }
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var one = nextIntArray();
        var a = one[0];
        var b = one[1];
        var c = one[2];
        var d = one[3];
        var two = nextIntArray();
        var x = two[0];
        var y = two[1];
        var x1 = two[2];
        var y1 = two[3];
        var x2 = two[4];
        var y2 = two[5];
        if((x1 == x2 && (a > 0 || b > 0))|| (y1 == y2 && (c > 0 || d > 0))){
          output[i] = "NO";
        }else{
          var diffX = b - a;
          var diffY = d - c;
          if(diffX >= x1 && diffX <= x2 && diffY >= y1 && diffY <= y2){
            output[i] = "YES";
          }else{
            output[i] = "NO";
          }
        }
    }
    myout(myconv(output,9));
}

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
function nextInt(){return myconv(next(),1);}
function nextStrArray(){return myconv(next(),2);}//半角スペース分割
function nextIntArray(){return myconv(next(),4);}//半角スペース + 数値化
function nextCharArray(){return myconv(next(),6);}//1文字分割
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
//atcoderのサンプルは最後に改行入れること
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = nextInt();
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var one = nextIntArray();
        var a = one[0];
        var b = one[1];
        var c = one[2];
        var d = one[3];
        var two = nextIntArray();
        var x = two[0];
        var y = two[1];
        var x1 = two[2];
        var y1 = two[3];
        var x2 = two[4];
        var y2 = two[5];
        if(x1 == x2 && y1 == y2){
          output[i] = "NO";
        }else{
          var diffX = b - a;
          var diffY = d - c;
          if(diffX >= x1 && diffX <= x2 && diffY >= y1 && diffY <= y2){
            output[i] = "YES";
          }else{
            output[i] = "NO";
          }
        }
    }
    myout(myconv(output,9));
}


One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.In order not to get lost, Vasya decided to act as follows.   Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.  Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).

print(function(n, p) {
	var i, j, ans = 0,
		mod = 1000000007,
		dp = new Int32Array(n + 2);

	n++;

	for (i = 1; i <= n; i++)
		dp[i] = 2;

	for (i = 1; i <= n; i++)
		for (j = p[i]; j < i; j++)
			dp[i] = (dp[i] + dp[j]) % mod;

	return dp[n] - 2;

}(+readline(), ('0 ' + readline() + ' 1').split(' ').map(Number)));

print(function(n, p) {
	var i, j, ans = 0,
		mod = 1000000007,
		dp = new Int32Array(n + 1);

	for (i = 1; i <= n; i++)
		dp[i] = 2;

	for (i = 1; i <= n; i++)
		for (j = p[i]; j < i; j++)
			dp[i] = (dp[i] + dp[j]) % mod;

	for (i = 1; i <= n; i++)
		ans = (ans + dp[i]) % mod;

	return ans;

}(+readline(), ('0 ' + readline()).split(' ').map(Number)));


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

var n = Number( readline() );
var arr = readline().split(' ');
var min = +arr[0];
var max = +arr[0];

for (var i = 0; i < arr.length; i++) {
	min = Math.min(min, arr[i]);
	max = Math.max(max, arr[i]);
}

var result = max - min + 1 - n;
print(result);

var n = +readline(),min = Number.MAX_VALUE, max = -1;
readline().split(' ').forEach(x=>{x = +x;min = Math.min(min,x);max = Math.max(max,x)});
print(Math.abs(max-min+1-n));

var n = Number(readline());

var input = readline().split(' ');
var result = 0;

input.sort(function(a,b) {
  return a-b;
});

for(var i=0; i<n-1; i++) {
  result += input[i+1]-input[i]-1;
}

print(result);

"use strict";

var length = parseInt(readline());

var maxNumber = void 0,
  minNumber = void 0;
readline()
  .split(" ")
  .map(function(value, index) {
    value = parseInt(value);

    if (index === 0) {
      maxNumber = value;
      minNumber = value;
    }

    if (maxNumber < value) maxNumber = value;
    if (minNumber > value) minNumber = value;
  });

write(maxNumber - minNumber + 1 - length + "\n");

var keyNumber = +readline();
var keyCurrent = readline().split(' ').sort(function(a, b){return a - b});
var first = keyCurrent[0],
    end = keyCurrent[keyNumber - 1];

//write(keyCurrent)
write((end - first + 1) - keyNumber)

var n = Number(readline());
var a = readline().split(' ').sort((a,b)=>{return a-b}).map(e=>parseInt(e));

var res = a[a.length-1] - a[0] + 1;
res = res -n
print(res)

readline()
var input = readline().split(' ').sort(function(a,b){return a-b;});

 var calc = 0;
 function myFunction(a, b) {return b - a;}

for(var x=0;x<input.length ;x++)
{
var r =  (myFunction(input[x],input[x+1]) - 1)
if (r > 0){calc+=r}

}
print(calc);

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
rl.on('line', (input) => {
    if (l === 0) { l++ }
    else {
        rl.close();
        let arr = input.split(" ").map(x => parseInt(x))
        arr.sort(function sortNumber(a, b) {
            return a - b;
        })
        let cnt = 0
        for (let i = 0; i < arr.length - 1; i++) {
            if ((arr[i] + 1) !== arr[i+1]) {
                cnt+=arr[i+1]-arr[i]
                cnt--
            }
        }
        console.log(cnt)
        return 0;
    }
})

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var output = 0;
  var list = nextIntArray();
  list.sort(function(a,b){
  	return a - b;
  });
  for(var i = 0; i < N - 1; i++){
    output += list[i + 1] - list[i] - 1;
  }
  myout(output);
}

let input ='';

process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data',(data)=>input+=data);

process.stdin.on('end',()=>{
   let count=0;
   input = input.split('\n');
   const arr = input[1].split(' ').map((item) => parseInt(item))
   arr.sort((a,b)=>b-a)

   for(let i = 0; i < arr.length-1;i++){
       count+=arr[i]-arr[i+1] - 1
   }
   console.log(count)
}
)

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  const arr = d.split(' ').map(Number).sort((a, b) => a - b);
  const min = arr[0];
  const max = arr[arr.length - 1];
  const ans = max - min - (arr.length - 1);

  console.log(ans);
  c++;
});

const stdin = process.stdin;
stdin.setEncoding( 'utf8' );
stdin.on( 'data', function( rawInput ){
    const inputLines = rawInput.split('\n');
    const n = parseInt(inputLines[0]);
    const indices = splitAndConvert(inputLines[1], n);
    const result = solve(indices, n);
    console.log(result);
});

function splitAndConvert(stringOfNumbers, numOfValid) {
	return stringOfNumbers.split(' ').slice(0, numOfValid).map(function(num) {
		return parseInt(num);
	});
}

function solve(indices, n) {
    const max = Math.max.apply(null, indices);
    const min = Math.min.apply(null, indices);
    const expectedN = max - min + 1;
    return expectedN - n;
}

const input = [];

const RL = require('readline').createInterface({
   input : process.stdin,
   output : process.stdout
});

RL.on('line', (line) => {
    input.push(line);
});

function fact(num)
{
    if(num === 0)
        return 1;
    return num * fact(num-1);
}

RL.on('close', () => {
    const n = parseInt(input[0], 10);
    const data = []; input[1].split(' ').forEach( i => data.push(parseInt(i, 10)) );
    data.sort((a, b) => a-b);
    let answer = 0;
    for(let i = 1; i < n; i += 1) {
        if(data[i-1]+1 !== data[i]) {
            answer += data[i] - data[i-1] - 1;
        }
    }
    console.log(answer);
});

'use strict'
process.stdin.on('data', data => {
  data = data.toString().split('\n')
  data.shift()
  let arr = data.shift().split(' ').map(a => parseInt(a))
  arr = arr.sort((a, b) => a - b)
  let ans = 0
  for (let i = 1; i < arr.length; i++) {
    ans += arr[i] - arr[i - 1] - 1
  }
  console.log(ans)
})

var n = Number(readline());
var a = readline().split(' ').sort((a,b)=>{return a-b}).map(e=>parseInt(e));
var res = a[a.length-2] - n;

print(res)

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
rl.on('line', (input) => {
    if (l === 0) { l++ }
    else {
        rl.close();
        let arr = input.split(" ").map(x => parseInt(x))
        let cnt = 0
        for (let i = 0; i < arr.length - 1; i++) {
            if ((arr[i] + 1) !== arr[i]) {
                cnt++
            }
        }
        console.log(cnt)
        return 0;
    }
})

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
rl.on('line', (input) => {
    if (l === 0) { l++ }
    else {
        rl.close();
        let arr = input.split(" ").map(x => parseInt(x))
        let cnt = 0
        for (let i = 0; i < arr.length - 1; i++) {
            if ((arr[i] + 1) !== arr[i+1]) {
                cnt++
            }
        }
        console.log(cnt)
        return 0;
    }
})

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
rl.on('line', (input) => {
    if (l === 0) { l++ }
    else {
        rl.close();
        let arr = input.split(" ").map(x => parseInt(x))
        arr.sort()
        let cnt = 0
        for (let i = 0; i < arr.length - 1; i++) {
            if ((arr[i] + 1) !== arr[i+1]) {
                cnt++
            }
        }
        console.log(cnt)
        return 0;
    }
})

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let l = 0;
rl.on('line', (input) => {
    if (l === 0) { l++ }
    else {
        rl.close();
        let arr = input.split(" ").map(x => parseInt(x))
        arr.sort()
        let cnt = 0
        for (let i = 0; i < arr.length - 1; i++) {
            if ((arr[i] + 1) !== arr[i+1]) {
                cnt+=arr[i+1]-arr[i]
            }
        }
        console.log(cnt)
        return 0;
    }
})


Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.

Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.

Print exactly one number — the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".

var c = 0, ans = 0;
readline().replace(/(heavy)|(metal)/g, function(_, a, b) {
	if (a) c++;
	else ans += c;
});
print(ans);

var c = 0, ans = 0;
readline().replace(/heavy|metal/g, function(a) {
	if (a === 'heavy') c++;
	else ans += c;
	return '';
});
print(ans);

var c = 0, ans = 0;
readline().replace(/heavy|metal/g, function(a) {
	if (a === 'heavy') c++;
	else ans += c;
});
print(ans);

;(function () {

	print(function (s) {

		var t = [];

		['heavy', 'metal'].forEach(function (e, i) {
			var pos = -1;
			while (true) {
				pos = s.indexOf(e, pos + 1);
				if (pos !== -1) t.push([i, pos]);
				else break;
			}
		});

		t = t.sort(function (a, b) { return a[1] - b[1]; }).map(function (e) { return e[0]; });

		var l = 0;
		for (var i = 0, _i = t.length; i < _i; i++) {
			if (t[i] === 0) l++;
			else t[i] = l;
		}

		return t.reduce(function (p, e) { return p + e; }, 0) || 0;

	}(readline()));

}.call(this));


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,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.For each $$$i$$$ ($$$1\le i\le n$$$), you're asked to choose a $$$j$$$ ($$$1\le j\le m$$$) and let $$$c_i=a_i\& b_j$$$, where $$$\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).

Print one integer: the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$.

const THRESHOLD = Math.pow(2, 9);

const main = () => {
  readline();

  const A = readline()
    .split(" ")
    .map((i) => Number(i));
  const B = readline()
    .split(" ")
    .map((i) => Number(i));

  var minResult = Infinity;

  for (var result = 0; result < THRESHOLD; result++) {
    var canReachResult = true;

    for (var i = 0; i < A.length; i++) {
      var canReachCurrentResult = false;

      for (var j = 0; j < B.length; j++) {
        if (((A[i] & B[j]) | result) === result) {
          canReachCurrentResult = true;
          break;
        }
      }

      if (!canReachCurrentResult) {
        canReachResult = false;
        break;
      }
    }

    if (canReachResult) {
      minResult = Math.min(minResult, result);
    }
  }

  return minResult;
};

print(main());

var readline=require("readline");
var rl=readline.createInterface({
    input:process.stdin,
    output:process.stdout
});
var arr=[],a,b,n,m;
rl.on('line',function(inp){
    arr.push(inp);
    var len=arr.length;
    if(len===1){
        n=parseInt(arr[0].split(' ')[0]);
        m=parseInt(arr[0].split(' ')[1]);
    }else if(len===2){
        a=arr[1].split(' ');
        for(var i=0;i<n;i++) a[i]=parseInt(a[i]);
    }else if(len===3){
        b=arr[2].split(' ');
        for(var i=0;i<m;i++) b[i]=parseInt(b[i]);
        var C=Math.pow(2,9),vis=new Array(201);
        for(var i=0;i<201;i++) vis[i]=new Array(C+1).fill(0);
        for(var i=0;i<n;i++){
            for(var j=0;j<m;j++){
                var ab=a[i]&b[j];
                for(var k=0;k<C+1;k++){
                    if(i>0&&vis[i-1][k]) vis[i][k|ab]=1;
                }
                if(i===0) vis[i][ab]=1;
            }
        }
        for(var i=0;i<=C;i++){
            if(vis[n-1][i]){
                console.log(i);
                process.exit(0);
            }
        }
    }
});

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readLine() {
    return inputString[currentLine++];
}

function main() {
  const [n, m] = readLine().split(/\s/).map(Number)
  const as = readLine().split(/\s/).map(Number)
  const bs = readLine().split(/\s/).map(Number)
  const cCandidates = []
  let max = 0
  for (const a of as) {
    const cCandidate = bs.map(b => a & b)
    cCandidates.push(cCandidate)
    max = Math.max(max, Math.min.apply(null, cCandidate))
  }
  const cs = []
  for (const cCandidate of cCandidates) {
    cs.push(cCandidate.sort((a, b) => (a | max) - (b | max))[0])
  }
  console.log(cs.reduce((acc, curr) => acc | curr))
}

const main = () => {
  readline();

  const A = readline()
    .split(" ")
    .map((i) => Number(i));
  const B = readline()
    .split(" ")
    .map((i) => Number(i));

  var result = 0;

  for (var i = 0; i < A.length; i++) {
    var currMin = A[i] & B[0];

    for (var j = 1; j < B.length; j++) {
      if ((result | (A[i] & B[j])) < (result | currMin)) {
        currMin = A[i] & B[j];
      }
    }

    result |= currMin;
  }

  return result;
};

print(main());