You are given a sequence $$$a$$$, initially consisting of $$$n$$$ integers.You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).To achieve this, you choose some integer $$$x$$$ that occurs at least once in $$$a$$$, and then perform the following operation any number of times (possibly zero): choose some segment $$$[l, r]$$$ of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains $$$x$$$. More formally, you choose some contiguous subsequence $$$[a_l, a_{l + 1}, \dots, a_r]$$$ such that $$$a_i \ne x$$$ if $$$l \le i \le r$$$, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the $$$(r+1)$$$-th is now $$$l$$$-th, the element that was $$$(r+2)$$$-th is now $$$(l+1)$$$-th, and so on (i. e. the remaining sequence just collapses).Note that you can not change $$$x$$$ after you chose it.For example, suppose $$$n = 6$$$, $$$a = [1, 3, 2, 4, 1, 2]$$$. Then one of the ways to transform it in two operations is to choose $$$x = 1$$$, then:  choose $$$l = 2$$$, $$$r = 4$$$, so the resulting sequence is $$$a = [1, 1, 2]$$$;  choose $$$l = 3$$$, $$$r = 3$$$, so the resulting sequence is $$$a = [1, 1]$$$. Note that choosing $$$x$$$ is not an operation. Also, note that you can not remove any occurrence of $$$x$$$.Your task is to find the minimum number of operations required to transform the sequence in a way described above.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine().split(" ").map(Number);
    const map = new Map();

    for (let i = 0; i < len; i++) {
      const n = arr[i];
      if (map.has(n)) {
        let { index, count, frequency } = { ...map.get(n) };
        map.set(n, { index: i, count, frequency: frequency + 1 });
        if (Math.abs(index - i) > 1) {
          map.set(n, { index: i, count: count + 1 });
        }
      } else {
        if (i > 0) {
          map.set(n, { count: 1, index: i, frequency: 1 });
        } else {
          map.set(n, { count: 0, index: i, frequency: 1 });
        }
      }
    }
    let [min, maxFrequence] = [Infinity, 0];
    for (let [key, obj] of map) {
      let { count, index, frequency } = obj;
      if (index !== len - 1) count++;
      min = Math.min(min, count);
      maxFrequence = Math.max(maxFrequence, frequency);
    }

    if (len === 1) console.log(0);
    else if (maxFrequence === 1) console.log(1);
    else console.log(min);
  }
}

//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){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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 t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = {};
		for(var j = 0; j < N; j++){
			if(map[list[j]] == null){
				map[list[j]] = [];
			}
			map[list[j]].push(j);
		}

		var keys = Object.keys(map);
		var count = N + 1;
		if(keys.length == 1){
			count = 0;
		}
		for(var j = 0; j < keys.length; j++){
			var check = map[keys[j]];
			var tmpCount = 0;
			if(check[0] != 0){
				tmpCount++;
			}
			if(check[check.length - 1] != N - 1){
				tmpCount++;
			}
			for(var k = 0; k < check.length - 1; k++){
				if(check[k] + 1 != check[k + 1]){
					tmpCount++;
				}
			}
			count = Math.min(count, tmpCount);
		}
		output[i] = count;
	}
	myout(myconv(output, 9));
}

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

let stdinInput = '';

process.stdin.on('data', input => {
  stdinInput += input;
})

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;

    while (i <= testCases) {
      const s = data[i + 1].trim().split(' ').map(Number);
      // let a = data[i].trim() * 1;
      const n = data[i] * 1;
      // const p = BigInt(s[0]);
      // const q = BigInt(s[1]);
      // s.sort((a, b) => b - a);
      let obj = {};
      // console.log(s);
      // let first = true;

      for (let j = 0; j < n; j += 1) {
        if (obj[s[j]]) obj[s[j]].push(j);
        else {
          obj[s[j]] = [j];
          // obj[s[j]]['count'] = 1;
          // obj[s[j]]['index'] = j + 1;
        }
      }

      let uq = false;
      let idx = Number.MAX_SAFE_INTEGER;
      // console.log(obj);

      for (let key in obj) {
        if (obj[key].length > 1) uq = true;
        if (obj[key].length === n) {idx = 0; break;}
        let temp = 0;
          if (obj[key][0] > 0) temp += 1;
          for (let j = 1; j < obj[key].length; j += 1) {
            if (obj[key][j] - obj[key][j - 1] > 1) temp += 1;
          }
          if (obj[key][obj[key].length - 1] < n - 1) temp += 1;
        idx = Math.min(idx, temp);
      }

      if (n === 1) console.log(0);
      else console.log(uq ? idx : 1);
      i += 2;
    }

}

"use strict";

(() => {

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

    let curLine = 0, allLines = [];

    let nextLine = () => {
        if(curLine == allLines.length) throw new ReferenceError("No more input in the buffer");
        return allLines[curLine++]
    };

    readline.on("line", line => { allLines.push(line); });
    readline.on("close", () => { main(nextLine) });

})();

function main(nextLine) {
    let t = Number(nextLine());

    while(t--) {
        let n = Number(nextLine());
        let ara = nextLine().split(" ").map(x => Number(x));

        let ase = new Array(n+1).fill(false), cnt = new Array(n+1).fill(0);

        ara.forEach((element, index) => {
            ase[element] = true;
            if(index && ara[index] !== ara[index-1]) cnt[element]++;
        });

        let mn = n;
        for(let i = 1; i <= n; i++) {
            if(ase[i]) mn = Math.min(mn, cnt[i]+(ara[n-1] !== i));
        }

        console.log(mn);
    }
}

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

let lines = [];

rl.on('line', (data) => {
    lines.push(data);
    if(lines.length > 0 && 2 * parseInt(lines[0]) === lines.length - 1) {
	rl.close();
	main();
    }
});

async function main() {
    let t = parseInt(lines[0]);
    for(let i = 1; i <= 2 * t; i += 2) {
	let n = parseInt(lines[i]);
	const arr = lines[i + 1].split(' ').map(x => parseInt(x));

	let map = {};
	for(const val of arr) {
	    map[val] = 1;
	}

	for(let j = 1; j < n; j++) {
	    if(arr[j] != arr[j - 1])
		map[arr[j]]++;
	}

	map[arr[n - 1]]--;
	let ans = 9999999;
	for(const v in map) {
	    ans = Math.min(ans, map[v]);
	}

	console.log(ans);
    }
}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const p="local"===process.argv[2],f=t=>{if(p){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function h(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:a,nextNumbers:h,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){p&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t]=i.default.nextNumbers(),e=i.default.nextNumbers(),r=[],n=Array(t+1).fill(0),o=e[0],s=!0;for(let r=0;r<t;++r)e[r]!=o&&(s=!1);r.push(e[0]);for(let n=1;n<t;++n)e[n]!=e[n-1]&&r.push(e[n]);let u=r.length;for(let t=0;t<u;++t)n[r[t]]++;if(s)return void i.default.puts(0);if(1==n[r[0]])return void i.default.puts(1);let l=t;for(let t=0;t<u;++t){let e=n[r[t]]+1;r[0]==r[t]&&e--,r[u-1]==r[t]&&e--,l=[l,e].min()}i.default.puts(l)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let b: number[] = []
//
//   let cnt = Array(n + 1).fill(0)
//
//   let x = a[0]
//
//   let allEq = true
//
//   for (let i = 0; i < n; ++i) {
//     if (a[i] != x) {
//       allEq = false
//     }
//   }
//
//   b.push(a[0])
//
//   for (let i = 1; i < n; ++i) {
//     if (a[i] != a[i - 1]) {
//       b.push(a[i])
//     }
//   }
//
//   // io.debug(b)
//
//   let m = b.length
//
//   for (let i = 0; i < m; ++i) {
//     cnt[b[i]]++
//   }
//
//   if (allEq) {
//     io.puts(0)
//     return
//   }
//
//   if (cnt[b[0]] == 1) {
//     io.puts(1)
//     return
//   }
//
//   let best = n
//
//   for (let i = 0; i < m; ++i) {
//     let candidate = cnt[b[i]] + 1
//
//     if (b[0] == b[i]) {
//       candidate--
//     }
//
//     if (b[m - 1] == b[i]) {
//       candidate--
//     }
//
//     best = [best, candidate].min()
//   }
//
//   io.puts(best)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

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();
    });

    C();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function A(){
    let t = pi(readline());
    while(t){
        t--;
        let n = pi(readline());
        let res = '';
        for(let i = 1; i <= n; i++){
            if(i !== n){
                res += ` ${i+1}`;
            }else{
                res += ` ${1}`;
            }
        }

        console.log(res.trim());
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let x = readline().split(' ');
        let a = new Array(n);
        let max = 0;
        for(let i = 0; i < n; i++)
            max = Math.max(max, pi(x[i]));
        let map = new Array(max+2);
        let rMap = new Array(max+2);

        for(let i = 0; i < n; i++){
            a[i] = pi(x[i]);
            if(map[a[i]] !== undefined){
                map[a[i]] += 1;
                rMap[a[i]] = i;
            }else{
                map[a[i]]  = 1;
                rMap[a[i]] = i;
            }
        }

        let min = 99999999999;
        for(let i = 0; i < a.length; i++){
            if(map[a[i]] === 1){
                min = Math.min(min, a[i]);
            }
        }

        console.log(min === 99999999999 ? -1 : rMap[min]+1);
    }
}

function C(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));
        let max = 0;
        for(let i = 0; i < n; i++)
            max = Math.max(max, a[i]);
        let map = new Array(max + 2);
        //map.fill(0);
        for(let i = 0; i < n; i++){
            if(i === 0){
                map[a[i]] = 1;
                continue;
            }

            if(a[i] !== a[i-1]){
                if(map[a[i]] !== undefined){
                    map[a[i]] += 1;
                }else{
                    map[a[i]]  = 1;
                }
            }
        }

        let min = 99999999;
        for(let i = 0; i < n; i++){
            if(map[a[i]] !== undefined){
                if(a[i] === a[0] && a[i] === a[n-1]){
                    min = Math.min(min, map[a[i]]-1);
                }else if(a[i] === a[0] || a[i] === a[n-1]){
                    min = Math.min(min, map[a[i]]);
                }else{
                    min = Math.min(min, map[a[i]]+1);
                }
            }
        }

        console.log(min === 99999999 ? 0 : min);
    }
}

let getFactors = (n) => {
    let i = 2;
    let res = [];
    while(i*i <= n){
        if(n%i === 0)
            res.push([i,n/i]);
        i++;
    }
    return res;
}

function D(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let dp = new Array(Math.floor(n+1));
        dp.fill(1);

        for(let i = 0; i < dp.length; i++){
            let f = getFactors(i);
            if(f.length !== 0){
                for(let j = 0; j < f.length; j++){
                    if(f[j][1] % f[j][0] === 0)
                        dp[i] = Math.max(dp[i], dp[f[j][0]]+dp[f[j][1]]);
                }
            }
        }

        let f = getFactors(n);
        let max = 1;
        if(f.length > 0){
            for(let i = 0; i < f.length; i++){
                if(f[i][1] % f[i][0] === 0)
                    max = Math.max(max, dp[f[i][0]]+dp[f[i][1]]);
            }
        }
        console.log(max);
    }
}

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}

// utils
const MOD = 1e9 + 7;
const mod = (n) => ((n % MOD) + MOD) % MOD;
const add = (a, b) => mod(mod(a) + mod(b));
const sub = (a, b) => mod(mod(a) - mod(b));
function mul() {
  for (var a = arguments, r = a[0], i = a.length; --i; )
    r = ((((r >> 16) * a[i]) % MOD) * 65536 + (r & 65535) * a[i]) % MOD;
  return r;
}
function inv(b) {
  for (var a = MOD, u = 0, v = 1, t; b; v = t)
    (t = (a / b) | 0), (a -= t * b), (u -= t * v), (t = a), (a = b), (b = t), (t = u), (u = v);
  u %= MOD;
  return u < 0 ? u + MOD : u;
}
function pow(base, n) {
  if (n === 0) return 1;
  let p = pow(base, Math.floor(n / 2));
  let res = mul(mod(p), mod(p));
  if (n % 2 === 1) res = mul(mod(res), base);
  return res;
}
function highestOneBit(i) {
  i |= i >> 1;
  i |= i >> 2;
  i |= i >> 4;
  i |= i >> 8;
  i |= i >> 16;
  return i - (i >>> 1);
}
function permutation(arr, len, store = "", permutations = []) {
  if (store.length === len) {
    permutations.push(store);
    return;
  }
  for (let i = 0; i < arr.length; i++) {
    const newArr = [...arr];
    const newChar = newArr.splice(i, 1);
    permutation(newArr, len, store.concat(newChar), permutations);
  }
  return permutations;
}

function main() {
  let t = +readLine();
  while (t--) {
    const len = +readLine();
    const arr = readLine().split(" ").map(Number);
    const map = new Map();

    for (let i = 0; i < len; i++) {
      const n = arr[i];
      if (map.has(n)) {
        let { index, count, frequency } = { ...map.get(n) };
        map.set(n, { index: i, count, frequency: frequency + 1 });
        if (Math.abs(index - i) > 1) {
          map.set(n, { index: i, count: count + 1 });
        }
      } else {
        if (i > 0) {
          map.set(n, { count: 1, index: i, frequency: 1 });
        } else {
          map.set(n, { count: 0, index: i, frequency: 1 });
        }
      }
    }
    let [min, maxFrequence] = [Infinity, 0];
    for (let [key, obj] of map) {
      let { count, index, frequency } = obj;
      if (index !== len - 1) count++;
      min = Math.min(min, count);
      maxFrequence = Math.max(maxFrequence, frequency);
    }

    if (maxFrequence === 1) console.log(1);
    else console.log(min);
  }
}

//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){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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 t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = {};
		var isZero = -1;
		for(var j = 0; j < N; j++){
			if(j == 0){
				isZero = list[j];
			}
			if(map[list[j]] == null){
				map[list[j]] = [j];
			}else{
				if(map[list[j]][map[list[j]].length - 1] == j - 1){
					map[list[j]][map[list[j]].length - 1] = j;
				}else{
					map[list[j]].push(j);
				}
			}
		}

		var keys = Object.keys(map);
		var count = N + 1;
		if(keys.length == 1){
			count = 0;
		}
		for(var j = 0; j < keys.length; j++){
			var check = map[keys[j]];
			if(check.length == 1){
				if(check[0] == 0 || check[0] == N - 1){
					count = Math.min(count, 1);
				}else{
					count = Math.min(count, 2);
				}
			}else{
				var tmpCount = 0;
				if(check[0] == 0 || isZero == keys[j]){

				}else{
					tmpCount++;
				}
				if(check[check.length - 1] != N - 1){
					tmpCount++;
				}
				tmpCount += check.length - 1;
				count = Math.min(count, tmpCount);
			}
		}
		output[i] = count;
	}
	myout(myconv(output, 9));
}

//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){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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 t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = {};
		var isZero = -1;
		for(var j = 0; j < N; j++){
			if(j == 0){
				isZero = list[j];
			}
			if(map[list[j]] == null){
				map[list[j]] = [j];
			}else{
				if(map[list[j]][map[list[j]].length - 1] == j - 1){
					map[list[j]][map[list[j]].length - 1] = j;
				}else{
					map[list[j]].push(j);
				}
			}
		}

		var keys = Object.keys(map);
		var count = N + 1;
		if(keys.length == 1){
			count = 0;
		}
		for(var j = 0; j < keys.length; j++){
			var check = map[keys[j]];
			if(check.length == 1){
				if(check[0] == 0 || check[0] == N - 1){
					count = Math.min(count, 1);
				}else{
					count = Math.min(count, 2);
				}
			}else{
				var tmpCount = 0;
				if(check[0] == 0 || isZero != keys[j]){

				}else{
					tmpCount++;
				}
				if(check[check.length - 1] != N - 1){
					tmpCount++;
				}
				tmpCount += check.length - 1;
				count = Math.min(count, tmpCount);
			}
		}
		output[i] = count;
	}
	myout(myconv(output, 9));
}

//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){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
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 t = nextInt();
	var output = new Array(t);
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var list = nextIntArray(N);
		var map = {};
		for(var j = 0; j < N; j++){
			if(map[list[j]] == null){
				map[list[j]] = [j];
			}else{
				if(map[list[j]][map[list[j]].length - 1] == j - 1){
					map[list[j]][map[list[j]].length - 1] = j;
				}else{
					map[list[j]].push(j);
				}
			}
		}

		var keys = Object.keys(map);
		var count = N + 1;
		if(keys.length == 1){
			count = 0;
		}
		for(var j = 0; j < keys.length; j++){
			var check = map[keys[j]];
			if(check.length == 1){
				if(check[0] == 0 || check[0] == N - 1){
					count = Math.min(count, 1);
				}else{
					count = Math.min(count, 2);
				}
			}else{
				var tmpCount = 0;
				if(check[0] != 0){
					tmpCount++;
				}
				if(check[check.length - 1] != N - 1){
					tmpCount++;
				}
				tmpCount += check.length - 1;
				count = Math.min(count, tmpCount);
			}
		}
		output[i] = count;
	}
	myout(myconv(output, 9));
}

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

let stdinInput = '';

process.stdin.on('data', input => {
  stdinInput += input;
})

process.stdin.on('end', () => {
  main(stdinInput);
})

function main(data) {
    data = data.split('\n');
    const testCases = data[0] * 2;
    let i = 1;

    while (i <= testCases) {
      const s = data[i + 1].trim().split(' ').map(Number);
      // let a = data[i].trim() * 1;
      const n = data[i] * 1;
      // const p = BigInt(s[0]);
      // const q = BigInt(s[1]);
      // s.sort((a, b) => b - a);
      let obj = {};
      // console.log(s);
      // let first = true;

      for (let j = 0; j < n; j += 1) {
        if (obj[s[j]]) obj[s[j]].push(j);
        else {
          obj[s[j]] = [j];
          // obj[s[j]]['count'] = 1;
          // obj[s[j]]['index'] = j + 1;
        }
      }

      let uq = false;
      let idx = Number.MAX_SAFE_INTEGER;
      // console.log(obj);

      for (let key in obj) {
        if (obj[key].length > 1) uq = true;
        if (obj[key].length === n) {idx = 0; break;}
        let temp = 0;
          if (obj[key][0] > 0) temp += 1;
          for (let j = 1; j < obj[key].length; j += 1) {
            if (obj[key][j] - obj[key][j - 1] > 1) temp += 1;
          }
          if (obj[key][obj[key].length - 1] < n - 1) temp += 1;
        idx = Math.min(idx, temp);
      }

      console.log(uq ? idx : 1);
      i += 2;
    }

}

(()=>{"use strict";var t={675:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),Array.numbersMatrix=(t,e,r)=>{let n=[];null==t&&(e=t),null==r&&(r=0);for(let i=0;i<t;++i){let t=[];for(let n=0;n<e;++n)t.push(r);n.push(t)}return n},Array.prototype.sortAsc=function(){return this.sort(((t,e)=>t-e))},Array.prototype.sortDesc=function(){return this.sort(((t,e)=>e-t))},Array.prototype.max=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.max(t,this[e]);return t},Array.prototype.min=function(){if(0==this.length)return 0;let t=this[0];for(let e=1;e<this.length;++e)t=Math.min(t,this[e]);return t},Array.prototype.sum=function(){let t=0;for(let e=0;e<this.length;++e)t+=this[e];return t},Array.prototype.modSum=function(t){let e=0;for(let r=0;r<this.length;++r)e+=this[r],e%=t;return e},Array.prototype.avg=function(){return this.sum()/this.length},Array.prototype.groupBy=function(t){let e=new Map;for(let r=0;r<this.length;++r){const n=t(this[r]);e.has(n)?e.get(n).push(this[r]):e.set(n,[this[r]])}return e},Array.prototype.deepCopy=function(){let t=[];if(0==this.length)return t;let e=!1;Array.isArray(this[0])&&(e=!0);for(let r=0;r<this.length;++r)e?t.push(this[r].deepCopy()):t.push(this[r]);return t},Array.prototype.transpose=function(){let t=[];if(0==this.length)return[[]];for(let e=0;e<this[0].length;++e){let r=[];for(let t=0;t<this.length;++t)r.push(this[t][e]);t.push(r)}return t},Array.prototype.toString=function(){if(0==this.length)return"";if(!Array.isArray(this[0]))return this.join(" ");let t="";for(let e=0;e<this.length;++e)t+=this[e].join(" "),e!=this.length-1&&(t+="\n");return t}},312:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0});const i=n(r(747));let o="",s=[],u=0,l="";const p="local"===process.argv[2],f=t=>{if(p){if(s=i.default.readFileSync("input.txt").toString().trim().split("\n").map((t=>t.trim())),t(),i.default.writeFileSync("output.txt",l),console.log(l),i.default.readFileSync("expected.txt").toString().trim()==l.trim()){const{exec:t}=r(129);t("osascript -e 'display notification \"✅ AC!!\"'")}}else process.stdin.resume(),process.stdin.setEncoding("utf-8"),process.stdin.on("data",(t=>{o+=t})),process.stdin.on("end",(e=>{s=o.trim().split("\n").map((t=>t.trim())),t(),console.log(l)}))};function a(){return s[u++]}function h(){return a().split(" ").map((t=>parseFloat(t)))}function c(){return a().split("")}e.default={runMain:f,runEachTest:t=>{f((()=>{let[e]=h();for(;e>0;)t(),e--}))},readline:a,nextNumbers:h,nextBigNumbers:function(){return a().split(" ").map((t=>BigInt(t)))},nextNumbersMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(h());return e},nextCharacters:c,nextCharacterMatrix:function(t){let e=[];for(let r=0;r<t;++r)e.push(c());return e},nextIntervalArray:function(t){let e=[];for(let r=0;r<t;++r){const[t,r]=h();e.push({a:t,b:r})}return e},put:function(t){l+=t},puts:function(t){l+=t+"\n"},debug:function(t){p&&console.log(t)}}},965:function(t,e,r){var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),r(675);const i=n(r(312));i.default.runEachTest((function(){let[t]=i.default.nextNumbers(),e=i.default.nextNumbers(),r=[],n=Array(t+1).fill(0),o=e[0],s=!0;for(let r=0;r<t;++r)e[r]!=o&&(s=!1);r.push(e[0]);for(let n=1;n<t;++n)r[n]!=r[n-1]&&r.push(e[n]);for(let e=0;e<t;++e)n[r[e]]++;if(s)return void i.default.puts(0);if(1==n[r[0]])return void i.default.puts(1);let u=t,l=r.length;for(let e=0;e<t;++e){let t=n[r[e]]+1;r[0]==r[e]&&t--,r[l-1]==r[e]&&t--,u=[u,t].min()}i.default.puts(u)}))},129:t=>{t.exports=require("child_process")},747:t=>{t.exports=require("fs")}},e={};!function r(n){if(e[n])return e[n].exports;var i=e[n]={exports:{}};return t[n].call(i.exports,i,i.exports,r),i.exports}(965)})();

// Solution written in typescript and compiled via webpack. Original source code below
// Happy Hacking 😜

// import './array'
//
// import io from './io'
//
// function main() {
//   let [n] = io.nextNumbers()
//   let a = io.nextNumbers()
//
//   let b: number[] = []
//
//   let cnt = Array(n + 1).fill(0)
//
//   let x = a[0]
//
//   let allEq = true
//
//   for (let i = 0; i < n; ++i) {
//     if (a[i] != x) {
//       allEq = false
//     }
//   }
//
//   b.push(a[0])
//
//   for (let i = 1; i < n; ++i) {
//     if (b[i] != b[i - 1]) {
//       b.push(a[i])
//     }
//   }
//
//   for (let i = 0; i < n; ++i) {
//     cnt[b[i]]++
//   }
//
//   if (allEq) {
//     io.puts(0)
//     return
//   }
//
//   if (cnt[b[0]] == 1) {
//     io.puts(1)
//     return
//   }
//
//   let best = n
//
//   let m = b.length
//
//   for (let i = 0; i < n; ++i) {
//     let candidate = cnt[b[i]] + 1
//
//     if (b[0] == b[i]) {
//       candidate--
//     }
//
//     if (b[m - 1] == b[i]) {
//       candidate--
//     }
//
//     best = [best, candidate].min()
//   }
//
//   io.puts(best)
// }
//
// io.runEachTest(main)
// // io.runMain(main)


Students of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≤ i ≤ n) has a best friend p[i] (1 ≤ p[i] ≤ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm:   on the first day of revising each student studies his own Mathematical Analysis notes,  in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≤ i ≤ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising:  a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising;  b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≤ ai ≤ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≤ bi ≤ n).

Print sequence n of different integers p[1], p[2], ..., p[n] (1 ≤ p[i] ≤ n). It is guaranteed that the solution exists and that it is unique.

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();
    });

    F();
});

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

function pi(a) {
    return parseInt(a);
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = pi(a[i]);

    return a;
}

function F(){
    let n = pi(readline());
    let a = ti(readline().split(' '));
    let b = ti(readline().split(' '));

    let p = new Array(n);
    for(let i = 0; i < n; i++){
        p[a[i]] = b[i];
    }

    console.log(p.join(' '));
}


You are given a sequence of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. You are also given $$$x$$$ integers $$$1, 2, \dots, x$$$.You are asked to insert each of the extra integers into the sequence $$$a$$$. Each integer can be inserted at the beginning of the sequence, at the end of the sequence, or between any elements of the sequence.The score of the resulting sequence $$$a'$$$ is the sum of absolute differences of adjacent elements in it $$$\left(\sum \limits_{i=1}^{n+x-1} |a'_i - a'_{i+1}|\right)$$$.What is the smallest possible score of the resulting sequence $$$a'$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n, x \le 2 \cdot 10^5$$$) — the length of the sequence and the number of extra integers. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$). The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the smallest sum of absolute differences of adjacent elements of the sequence after you insert the extra integers into it.

NoteHere are the sequences with the smallest scores for the example. The underlined elements are the extra integers. Note that there exist other sequences with this smallest score.   $$$\underline{1}, \underline{2}, \underline{3}, \underline{4}, \underline{5}, 10$$$  $$$\underline{7}, 7, \underline{6}, \underline{4}, 2, \underline{2}, \underline{1}, \underline{3}, \underline{5}, \underline{8}, 10$$$  $$$6, \underline{1}, 1, \underline{2}, 5, 7, 3, 3, 9, 10, 10, 1$$$  $$$1, 3, \underline{1}, 1, 2, \underline{2}, \underline{3}, \underline{4}, \underline{5}, \underline{6}, \underline{7}, \underline{8}, \underline{9}, \underline{10}$$$

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, insert] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, insert, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, insert, arr) {
    let min = 1
    let max = insert
    let ans = 0
    let pmin = Math.abs(min - arr[0])
    let pmax = Math.abs(max - arr[0])
    let vmin = Infinity
    let vmax = -Infinity
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        vmin = Math.min(vmin, x)
        vmax = Math.max(vmax, x)
        // after i
        const now = i + 1 < n ? Math.abs(x - arr[i + 1]) : 0
        ans += now
        const cmin = Math.abs(min - x) + (i + 1 < n ? Math.abs(min - arr[i + 1]) : 0)
        const cmax = Math.abs(max - x) + (i + 1 < n ? Math.abs(max - arr[i + 1]) : 0)
        pmin = Math.min(pmin, cmin - now)
        pmax = Math.min(pmax, cmax - now)
    }
    // console.log(ans, pmin, pmax)
    if (max > vmax) ans += pmax
    if (min < vmin) ans += pmin
    return ans
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const calc = (n, x, a)=>{
    let count = 0;

    let min = Infinity;
    let max = -1;
    let minPos = -1;
    let maxPos = -1;

    for (let i = 0; i < n; i++) {
        if (a[i] < min) {
            min = a[i];
            minPos = i;
        }
        if (a[i] > max) {
            max = a[i];
            maxPos = i;
        }
        if (i === 0) continue;
        count += Math.abs(a[i] - a[i - 1]);
    }

    // console.log('DEBUG count', count);

    let minLabel = undefined;

    let mins = [Infinity, Infinity, Infinity];

    if (min > 1) {
        if (minPos === 0) {
            count += min - 1;
            minLabel = 'left';
        } else if (minPos === n - 1) {
            count += min - 1;
            minLabel = 'right';
        } else {
            mins[1] = 2 * (min - 1);
            mins[0] = a[0] - 1;
            mins[2] = a[n - 1] - 1;
            minLabel = 'mid';
        }
    }

    // console.log('DEBUG count', count);

    let maxLabel = undefined;
    let maxs = [Infinity, Infinity, Infinity];

    if (max < x) {
        if (maxPos === 0) {
            count += x - max;
            maxLabel = 'left';
        } else if (maxPos === n - 1) {
            count += x - max;
            maxLabel = 'right';
        } else {
            maxLabel = 'mid';
            maxs[1] = 2 * (x - max);
            maxs[0] = x - a[0];
            maxs[2] = x - a[n - 1];

            // if (leftPlacement < maxRes && minLabel !== 'left') {
            //     maxRes = leftPlacement;
            // }
            // if (rightPlacement < maxRes && minLabel !== 'right') {
            //     maxRes = rightPlacement;
            // }
            // count += maxRes;
        }
    }

    if (minLabel !== 'mid' && maxLabel !== 'mid') {
        return count;
    } else if (minLabel === 'mid' && maxLabel !== 'mid') {
        let minMin = mins[1];
        if (maxLabel !== 'left' && mins[0] < minMin) {
            minMin = mins[0];
        }
        if (maxLabel !== 'right' && mins[2] < minMin) {
            minMin = mins[2];
        }
        count += minMin;
    } else if (maxLabel === 'mid' && minLabel !== 'mid') {
        let maxMin = maxs[1];
        if (minLabel !== 'left' && maxs[0] < maxMin) {
            maxMin = maxs[0];
        }
        if (minLabel !== 'right' && maxs[2] < maxMin) {
            maxMin = maxs[2];
        }
        count += maxMin;
    } else {
        let minRes = Infinity;

        for (let i = 0; i < 3; i++) {
            for (let j = 0; j < 3; j++) {
                if (i === j && i !== 1) continue;
                minRes = Math.min(minRes, mins[i] + maxs[j]);
            }
        }
        count += minRes;
    }

    // console.log('DEBUG count', count);

    return count;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [n, x] = ra();
        let a = ra();
        console.log(`${calc(n, x, a)}`);
    }
}

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, x, a) {
  if (n === 1) {
    console.log(Math.max(x, a[0]) - 1);
    return;
  }
  let min = 1,
      max = x,
      sum = 0;
  for (let i = 1; i < n; i++) {
    sum += Math.abs(a[i] - a[i - 1]);
  }
  let res = Infinity;
  for (let num of [min, max]) {
    res = Infinity;
    let t = 0;
    for (let i = 0; i <= a.length; i++) {
      let ans = 0;
      if (i === 0) {
        ans = sum + Math.abs(num - a[0]);
      } else if (i === a.length) {
        ans = sum + Math.abs(num - a[a.length - 1]);
      } else {
        ans = sum - Math.abs(a[i] - a[i - 1]) + Math.abs(a[i] - num) + Math.abs(a[i - 1] - num);
      }
      if (ans < res) {
        res = ans;
        t = i;
      }
    }
    a.splice(t, 0, num);
    sum = res;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const [n, x] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    solve(n, x, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();

const fs = require("fs");

const input = fs.readFileSync(0, "utf8").trim().split("\n");

const testCases = [];
let T;

function parseInput() {
  T = parseInt(input[0]);
  let index = 0;

  for (let i = 0; i < T; i++) {
    index++;
    const [n, x] = input[index].split(" ").map((item) => parseInt(item));
    index++;
    const a = input[index].split(" ").map((item) => parseInt(item));
    const testCase = {
      n,
      x,
      a,
    };

    testCases.push(testCase);
  }
}

function solution(testCase, index) {
  const { n, x, a } = testCase;
  // console.log(n, x, a);

  let result = a.reduce(
    (acc, val, i) => (i == 0 ? 0 : acc + Math.abs(val - a[i - 1])),
    0
  );

  // console.log("sum", result);

  const mini = Math.min(...a);
  const maxi = Math.max(...a);
  // console.log(mini, maxi);

  const miniRange = mini > 1 ? [1, Math.min(x, mini - 1)] : undefined;
  const maxiRange = maxi < x ? [maxi + 1, x] : undefined;

  // console.log(miniRange, maxiRange);

  if (miniRange) {
    const possibleSums = [];
    possibleSums.push(
      Math.max(Math.abs(a[0] - miniRange[0]), Math.abs(a[0] - miniRange[1]))
    );
    possibleSums.push(
      Math.max(
        Math.abs(a[n - 1] - miniRange[0]),
        Math.abs(a[n - 1] - miniRange[1])
      )
    );
    possibleSums.push((mini - miniRange[0]) * 2);
    // console.log("mini possibleSums", possibleSums);
    result += Math.min(...possibleSums);
  }

  if (maxiRange) {
    const possibleSums = [];
    possibleSums.push(
      Math.max(Math.abs(a[0] - maxiRange[0]), Math.abs(a[0] - maxiRange[1]))
    );
    possibleSums.push(
      Math.max(
        Math.abs(a[n - 1] - maxiRange[0]),
        Math.abs(a[n - 1] - maxiRange[1])
      )
    );
    possibleSums.push((maxiRange[1] - maxi) * 2);
    // console.log("maxi possibleSums", possibleSums);
    result += Math.min(...possibleSums);
  }

  console.log(result);
}

parseInput();

testCases.forEach(solution);

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, insert] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, insert, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, insert, arr) {
    let min = 1
    let max = insert
    let ans = 0
    let pmin = Math.abs(min - arr[0])
    let pmax = Math.abs(max - arr[0])
    let vmin = Infinity
    let vmax = -Infinity
    for (let i = 0; i < arr.length; i++) {
        const x = arr[i]
        vmin = Math.min(vmin, x)
        vmax = Math.max(vmax, x)
        // after i
        const now = i + 1 < n ? Math.abs(x - arr[i + 1]) : 0
        ans += now
        const cmin = Math.abs(min - x) + (i + 1 < n ? Math.abs(min - arr[i + 1]) : 0)
        const cmax = Math.abs(max - x) + (i + 1 < n ? Math.abs(max - arr[i + 1]) : 0)
        pmin = Math.min(pmin, cmin - now)
        pmax = Math.min(pmax, cmax - now)
    }
    // console.log(ans, pmin, pmax)
    if (max <= vmax) {
        return ans + pmin
    } else if (min >= vmin) {
        return ans + pmax
    } else {
        return ans
    }
}

const readline = require('readline')

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input);
})
rl.on('close', () => {
// (function() {
    // const lines = require('fs').readFileSync('test.in', 'utf8').split('\n')
    let l = 0;
    let t = +lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const [n, insert] = lines[l++].trim().split(' ').map(Number)
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, insert, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, insert, arr) {
    let min = 1
    let max = insert
    let ans = 0
    let pmin = Math.abs(min - arr[0])
    let pmax = Math.abs(max - arr[0])
    for (let i = 0; i < arr.length; i++) {
        // after i
        const x = arr[i]
        const now = i + 1 < n ? Math.abs(x - arr[i + 1]) : 0
        ans += now
        const cmin = Math.abs(min - x) + (i + 1 < n ? Math.abs(min - arr[i + 1]) : 0)
        const cmax = Math.abs(max - x) + (i + 1 < n ? Math.abs(max - arr[i + 1]) : 0)
        pmin = Math.min(pmin, cmin - now)
        pmax = Math.min(pmax, cmax - now)
    // console.log(ans, pmin, pmax)
    }
    return n === 1 ? ans + pmin : ans + pmin + pmax
}

const lines = [];
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => lines.push(line));
rl.on('close', main);
let rli = 0;
function readline() {
    return lines[rli++];
}

const ra = ()=>readline().split(' ').map(a=>+a);

function div(val, by){
    return (val - val % by) / by;
}

const cnk = (n, k) => {
    let res = 1;
    for (let i = 1; i <= k; i++)
        res = res * (n - k + i) / i;
    return Math.round(res + 0.01);
}

const calc = (n, x, a)=>{
    let count = 0;

    let min = Infinity;
    let max = -1;
    let minPos = -1;
    let maxPos = -1;

    for (let i = 0; i < n; i++) {
        if (a[i] < min) {
            min = a[i];
            minPos = i;
        }
        if (a[i] > max) {
            max = a[i];
            maxPos = i;
        }
        if (i === 0) continue;
        count += Math.abs(a[i] - a[i - 1]);
    }

    // console.log('DEBUG count', count);

    let minLabel = undefined;

    if (min > 1) {
        if (minPos === 0) {
            count += min - 1;
            minLabel = 'left';
        } else if (minPos === n - 1) {
            count += min - 1;
            minLabel = 'right';
        } else {
            count += 2 * (min - 1);
            minLabel = 'mid';
        }
    }

    // console.log('DEBUG count', count);

    if (max < x) {
        if (maxPos === 0) {
            count += x - max;
        } else if (maxPos === n - 1) {
            count += x - max;
        } else {
            let maxRes = 2 * (x - max);
            let leftPlacement = x - a[0];
            let rightPlacement = x - a[n - 1];

            if (leftPlacement < maxRes && minLabel !== 'left') {
                maxRes = leftPlacement;
            }
            if (rightPlacement < maxRes && minLabel !== 'right') {
                maxRes = rightPlacement;
            }
            count += maxRes;
        }
    }

    // console.log('DEBUG count', count);

    return count;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let [n, x] = ra();
        let a = ra();
        console.log(`${calc(n, x, a)}`);
    }
}

'use strict';

var readline = require('readline');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);

function solve(n, x, a) {
  if (n === 1) {
    console.log(Math.max(x, a[0]) - 1);
    return;
  }
  let min = 1,
      max = x,
      sum = 0;
  for (let i = 1; i < n; i++) {
    sum += Math.abs(a[i] - a[i - 1]);
  }
  let res = Infinity;
  for (let num of [min, max]) {
    res = Infinity;
    for (let i = 0; i <= n; i++) {
      if (i === 0) {
        res = Math.min(res, sum + Math.abs(num - a[0]));
      } else if (i === n) {
        res = Math.min(res, sum + Math.abs(num - a[n - 1]));
      } else {
        res = Math.min(res, sum - Math.abs(a[i] - a[i - 1]) + Math.abs(a[i] - num) + Math.abs(a[i - 1] - num));
      }
    }
    sum = res;
  }
  console.log(res);
}

async function main(read) {
  let t = Number(await read());
  while (t--) {
    const [n, x] = (await read()).split(' ').map(Number);
    const a = (await read()).split(' ').map(Number);
    solve(n, x, a);
  }
}

const rl = readline__default["default"].createInterface({
  input: process.stdin,
  output: process.stdout
});
void async function () {
  const inputs = [];
  let i = 0;
  for await (const line of rl) {
    inputs.push(line.trim());
  }
  function read() {
    return inputs[i++];
  }
  await main(read);
}();


There is an array $$$a$$$ with $$$n-1$$$ integers. Let $$$x$$$ be the bitwise XOR of all elements of the array. The number $$$x$$$ is added to the end of the array $$$a$$$ (now it has length $$$n$$$), and then the elements are shuffled.You are given the newly formed array $$$a$$$. What is $$$x$$$? If there are multiple possible values of $$$x$$$, you can output any of them.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of integers in the resulting array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 127$$$) — the elements of the newly formed array $$$a$$$. Additional constraint on the input: the array $$$a$$$ is made by the process described in the statement; that is, some value of $$$x$$$ exists.

For each test case, output a single integer — the value of $$$x$$$, as described in the statement. If there are multiple possible values of $$$x$$$, output any of them.

NoteIn the first test case, one possible array $$$a$$$ is $$$a=[2, 5, 4]$$$. Then $$$x = 2 \oplus 5 \oplus 4 = 3$$$ ($$$\oplus$$$ denotes the bitwise XOR), so the new array is $$$[2, 5, 4, 3]$$$. Afterwards, the array is shuffled to form $$$[4, 3, 2, 5]$$$.In the second test case, one possible array $$$a$$$ is $$$a=[1, 10, 6, 10]$$$. Then $$$x = 1 \oplus 10 \oplus 6 \oplus 10 = 7$$$, so the new array is $$$[1, 10, 6, 10, 7]$$$. Afterwards, the array is shuffled to form $$$[6, 1, 10, 7, 10]$$$.In the third test case, all elements of the array are equal to $$$6$$$, so $$$x=6$$$.In the fourth test case, one possible array $$$a$$$ is $$$a=[100, 100]$$$. Then $$$x = 100 \oplus 100 = 0$$$, so the new array is $$$[100, 100, 0]$$$. Afterwards, the array is shuffled to form $$$[100, 100, 0]$$$. (Note that after the shuffle, the array can remain the same.)

const tests = parseInt(readline());
for (var t=0; t < tests; t++) {
    var n = readline();
    var arr = readline().split(" ").map(x => parseInt(x));
    print(arr[0]);
}

var tests = parseInt(readline());
for (var t=0; t < tests; t++) {
    var n = readline();
    var arr = readline().split(' ').map(x => parseInt(x));
    print(arr[0]);
}

var tests = parseInt(readline());
for (var t=0; t < tests; t++) {
    var n = readline();
    var arr = readline().split(" ").map(x => parseInt(x));
    print(arr[0]);
}

var t = parseInt(readline());

while(t--){

var n = parseInt(readline());

var ar =[];
var i;

ar= readline().split(' ').map(x => parseInt(x));

print(ar[ar.length-1]);

}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    readline();
    var caseArray = readline().split(" ");
    print(caseArray[0]);
}

"use strict";
function toInt(x) {
    return parseInt(x);
}

let t = parseInt(readline());
while (t--) {
    let n = parseInt(readline());
    let a = readline().split(' ').map(toInt);
    outer: for (let ind = 0; ind < n; ind++) {
    	let xor = 0;
    	for (let i = 0; i < n; i++) {
    		if (i != ind) xor ^= a[i];
     	}
     	if (xor == a[ind]) {
     		print(xor);
     	    break outer;
     	}
    }
}

var t = +readline();

for(var i = 0; i< t; i ++) {

    var t1 = readline();
    var t2 = readline().split(' ').map((t) => +t);
    print(ShuffleArray(t2))

}

function ShuffleArray(arr){

  function checkArr(idx){
    // var shuff =

    var init = 0;
    for(var i = 0; i<arr.length;i++){
      if (idx != i) init ^= arr[i];
    }

    return init;

  }

  for(var j = 0; j<arr.length; j++){
    if (checkArr(j) === arr[j]){
      return arr[j]
    }
  }

  return -1

}

'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();

    for (let i = 0; i < N; i++) {
        let n = Number(readline());
        let arr = readline().split(' ').map(Number);
        let prefix = Array(n).fill(0);
        let suffix = Array(n).fill(0);

        for (let j = 1; j < n; j++) {
            prefix[j] = prefix[j - 1] ^ arr[j - 1];
            suffix[n - 1 - j] = suffix[n - j] ^ arr[n - j];
        }

        const result = arr.find((value, index) => prefix[index] ^ suffix[index] === value);
        output(result);
    }
}

process.stdin.resume();
process.stdin.setEncoding("utf-8");
//
let standardInputString = "";
let currentLine = 0;
//
process.stdin.on("data", (rawData) => {
  standardInputString += rawData;
});
process.stdin.on("end", (_) => {
  standardInputString = standardInputString
    .trim()
    .split("\n")
    .map((line) => {
      return line.trim();
    });
  main();
});

function readline() {
  return standardInputString[currentLine++];
}
function print(data) {
  console.log(data);
}

//line to array of integers
//readline().split(' ').map(Number)
//  let iter=parseInt(readline())
//multiple integer construction->const [a,b,c]=integer array

function main() {
  let q = parseInt(readline());
  for (let i = 0; i < q; i++) {
    let n = parseInt(readline());
    let num = readline().split(" ").map(Number);
    print(num[0]);
  }
}

'use strict';

function solve(n, a) {
  return a[0];
}

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);
});

var t = parseInt(readline());

while(t--){

var n = parseInt(readline());

var x ;
var i= 0;

for( i=0;i<n;i++){

   x= parseInt(readline());

}

print(x);

}

var t = parseInt(readline());

while(t--){

var n = parseInt(readline());

var x =n;var i= 0;

for( i=0;i<x;i++){

   x= parseInt(readline());

}

print(x);

}


Parsa has a humongous tree on $$$n$$$ vertices.On each vertex $$$v$$$ he has written two integers $$$l_v$$$ and $$$r_v$$$.To make Parsa's tree look even more majestic, Nima wants to assign a number $$$a_v$$$ ($$$l_v \le a_v \le r_v$$$) to each vertex $$$v$$$ such that the beauty of Parsa's tree is maximized.Nima's sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of $$$|a_u - a_v|$$$ over all edges $$$(u, v)$$$ of the tree.Since Parsa's tree is too large, Nima can't maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa's tree.

The first line contains an integer $$$t$$$ $$$(1\le t\le 250)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2\le n\le 10^5)$$$ — the number of vertices in Parsa's tree. The $$$i$$$-th of the following $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ $$$(1 \le l_i \le r_i \le 10^9)$$$. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ $$$(1 \le u , v \le n, u\neq v)$$$ meaning that there is an edge between the vertices $$$u$$$ and $$$v$$$ in Parsa's tree. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the maximum possible beauty for Parsa's tree.

NoteThe trees in the example:  In the first test case, one possible assignment is $$$a = \{1, 8\}$$$ which results in $$$|1 - 8| = 7$$$.In the second test case, one of the possible assignments is $$$a = \{1, 5, 9\}$$$ which results in a beauty of $$$|1 - 5| + |5 - 9| = 8$$$

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var os = require('os');

const stdin = process.stdin;
const stdout = process.stdout;
const integerRegex = /-?\d+/g;
const decimalRegex = /-?\d+(?:\.\d+)?/g;
class InputAndOutput {
    constructor() {
        this.lineIndex = 0;
        this.lines = [];
    }
    dried() {
        return this.lineIndex >= this.lines.length;
    }
    readLine() {
        const line = this.lines[this.lineIndex];
        this.lineIndex += 1;
        return line;
    }
    readIntegersOfLine() {
        const line = this.readLine();
        const m = line.match(integerRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    readNumsOfLine() {
        const line = this.readLine();
        const m = line.match(decimalRegex);
        if (m == null)
            return [];
        return m.map(x => Number(x));
    }
    print(content) {
        stdout.write(content);
    }
    async init() {
        const lines = await this.readLines();
        this.lines = lines;
    }
    readLines() {
        const buffers = [];
        return new Promise(resolve => {
            stdin.on('data', (buffer) => buffers.push(buffer));
            stdin.on('end', function () {
                const inputs = buffers.join('');
                const lines = inputs.split(os.EOL);
                resolve(lines);
            });
        });
    }
}
async function __main__(handle) {
    const io = new InputAndOutput();
    await io.init();
    handle(io);
}

const MAX_N = 1e5 + 10;
const dp = new Array(MAX_N);
for (let i = 0; i < dp.length; ++i)
    dp[i] = new Array(2);
function solve(N, vertexes, G) {
    for (let i = 0; i < N; ++i)
        dp[i][0] = dp[i][1] = -1;
    return Math.max(dfs(-1, 0, 0), dfs(-1, 0, 1));
    function dfs(p, u, dir) {
        if (dp[u][dir] !== -1)
            return dp[u][dir];
        let answer = 0;
        const value = vertexes[u][dir];
        for (const v of G[u]) {
            if (v === p)
                continue;
            answer += Math.max(dfs(u, v, 0) + Math.abs(value - vertexes[v][0]), dfs(u, v, 1) + Math.abs(value - vertexes[v][1]));
        }
        dp[u][dir] = answer;
        return answer;
    }
}
const vertexes = new Array(MAX_N);
const G = new Array(MAX_N);
__main__(function (io) {
    const T = Number(io.readLine());
    for (let kase = 1; kase <= T; ++kase) {
        const N = Number(io.readLine());
        for (let i = 0; i < N; ++i) {
            vertexes[i] = io.readIntegersOfLine();
            G[i] = [];
        }
        for (let i = 1; i < N; ++i) {
            const [u, v] = io.readIntegersOfLine();
            G[u - 1].push(v - 1);
            G[v - 1].push(u - 1);
        }
        const answer = solve(N, vertexes, G);
        io.print('' + answer + '\n');
    }
});

var stdin_input = "";
var stdin_input_itr;
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { stdin_input_itr = stdin_input.split('\n').values(); main(); });

const rl = () => stdin_input_itr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

let n, g, l, h;
let dp;

function dfs (u=0, p=-1) {
	for (const v of g[u]) {
		if (v == p) continue;
		dfs(v, u);
		dp[u][0] += Math.max(dp[v][0] + Math.abs(l[u] - l[v]), dp[v][1] + Math.abs(l[u] - h[v]));
		dp[u][1] += Math.max(dp[v][0] + Math.abs(h[u] - l[v]), dp[v][1] + Math.abs(h[u] - h[v]));
	}
}

function main () {
	let T = rn();
	while (T--) {
		n = rn();
		l = [], h = [];
		g = Array.from(Array(n), _ => []);
		for (let i = 0; i < n; i++) [l[i], h[i]] = rna();
		for (let i = 0; i < n - 1; i++) {
			let [u, v] = rna(); u--, v--;
			g[u].push(v);
			g[v].push(u);
		}

		dp = Array.from(Array(n), _ => [0, 0]);
		dfs();

		console.log(Math.max(dp[0][0], dp[0][1]));
	}
}

var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var lines = [];
rl.on('line', function(input) {
    lines.push(input);
});
rl.on('close', function() {
    var t = parseInt(lines[0]);
    var l = 1;
    for (var i = 0; i < t; i++) {
        var n = +lines[l++]
        var ranges = lines.slice(l, l + n).map(str => str.split(' ').map(Number))
        l += n
        var edges = lines.slice(l, l + n - 1).map(str => str.split(' ').map(Number))
        l += n - 1
        console.log(solve(n, ranges, edges));
    }
});

function solve(n, ranges, edges) {
    const adj = {}
    edges.forEach(([a, b]) => {
        a--
        b--
        adj[a] = adj[a] || []
        adj[b] = adj[b] || []
        adj[a].push(b)
        adj[b].push(a)
    })

    const dp = [[], []]
    dfs(dp, adj, 0, -1, ranges)
    return Math.max(dp[0][0], dp[1][0])
}

function dfs(dp, adj, u, p, ranges) {
    // dp[0][u] = max sum if `u` select min `au`
    // dp[1][u] = max sum if `u` select max `au`
    dp[0][u] = dp[1][u] = 0
    adj[u].forEach(v => {
        if (v === p) return

        dfs(dp, adj, v, u, ranges)
        dp[0][u] += Math.max(
            dp[0][v] + Math.abs(ranges[u][0] - ranges[v][0]),
            dp[1][v] + Math.abs(ranges[u][0] - ranges[v][1])
        )
        dp[1][u] += Math.max(
            dp[0][v] + Math.abs(ranges[u][1] - ranges[v][0]),
            dp[1][v] + Math.abs(ranges[u][1] - ranges[v][1])
        )
    })
}


A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?

The first line contains number n (1 ≤ n ≤ 1000) — the number of values of the banknotes that used in Geraldion.  The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the values of the banknotes.

Print a single line — the minimum unfortunate sum. If there are no unfortunate sums, print  - 1.

function sorting(a,n){
	var buf;
	for(i=0; i<= +(n-2); i++){
		for(x=i+1; x<=+(n-1); x++){
			if(+a[i]>+a[x]){
				buf = a[i];
				a[i] = a[x];
				a[x] = buf;
			}
		}
	}
}

function unluckySum(a,n){
	if(+a[0] == 1){
		write("-1");
	}
	else{
		write("1");
	}
}

var n = readline(), a = readline().split(" ");
sorting(a,n);
unluckySum(a,n);

function ProblemSolver() {
    this.HAS_TEST_CASES = false ;
    this.INPUT_FILE_NAME = "sample.in" ;
    this.OUTPUT_FILE_NAME = "sample.out" ;
    this.DO_OUTPUT_TO_FILE = false ;
    this.CLEAR_ARRAY_PER_CASE = false ;

    this.solveCase = function() {
        var res , i , j , fl , cn , a , b , c ;
        res = 0 ;
        this.arr = this.arr.sort( function( le , ri ) { return le - ri ; } ) ;
        if( this.arr[ 0 ] == 1 ) {
            res = -1 ;
        }
        else {
            res = 1 ;
        }
        print( res ) ;
    } ;

    this.init = function() {
        this.lim1 = 100010 ;
        this.lim2 = 110 ;
        this.cc = 1 ;
        this.ind = 1 ;
        this.n = 0 ;
        this.cn = 0 ;
        this.declareAndFillArrays() ;
    } ;

    this.getInput = function( irObj ) {
        var hasMoreInput , i ;
        hasMoreInput = true ;
        try {
        	this.n = irObj.nextInt() ;
            this.arr = [] ;
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr.push( irObj.nextInt() ) ;
            }
        }
        catch( ex ) {
            hasMoreInput = false ;
        }
        return hasMoreInput ;
    } ;

    this.clearArraysPerCase = function() {
        var i ;
        this.arr = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.arr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
    } ;

    this.clearPerCase = function() {
        this.cn = 0 ;
        this.cc++ ;
        if( this.CLEAR_ARRAY_PER_CASE == true ) {
            this.clearArraysPerCase() ;
        }
    } ;

    this.declareAndFillArrays = function() {
        var i , j ;
        this.srr = new Array() ;
        this.vis = new Array() ;
        this.arr = new Array() ;
        this.brr = new Array() ;
        this.memo = new Array() ;
        this.done = new Array() ;
        this.adjList = new Array() ;
        for( i = 0 ; i < this.lim1 ; i++ ) {
            this.srr.push( '' ) ;
            this.vis.push( 0 ) ;
            this.arr.push( 0 ) ;
            this.brr.push( 0 ) ;
            this.adjList.push( new Array() ) ;
        }
        for( i = 0 ; i < this.lim2 ; i++ ) {
            this.memo.push( new Array() ) ;
            this.done.push( new Array() ) ;
            for( j = 0 ; j < this.lim2 ; j++ ) {
                this.memo[ i ].push( -1 ) ;
                this.done[ i ].push( 0 ) ;
            }
        }
    } ;

    this.init() ;
}

function InputReader() {
    var self = this ;
    this.allLines = new Array() ;
    this.currrentLineNumber = 0 ;
    this.currrentCharacterIndex = 0 ;
    this.callBackFunction = null ;
    this.parentContext = null ;

    this.readAllLines = function() {
        var singleLine ;
        while( true ) {
            try {
                singleLine = readline() ;
                if( singleLine == null ) {
                    break ;
                }
            }
            catch( ex ) {
                break ;
            }
            this.allLines.push( singleLine ) ;
        }
    } ;

    this.readAllLinesFromRhino = function() {
        var brObj , line ;
        importPackage( java.io ) ;
        importPackage( java.lang ) ;
        brObj = new BufferedReader( new InputStreamReader( System[ 'in' ] ) ) ;
        this.allLines = [] ;
        while( true ) {
            line = brObj.readLine() ;
            if( line == null ) {
                break;
            }
            this.allLines.push( line ) ;
        }
    } ;

    this.readSingleLinesFromNodeJsJudgeServer = function( chunk ) {
        self.chunkData += chunk ;
    } ;

    this.readEndFromNodeJsJudgeServer = function() {
        self.parseRawData( self.chunkData ) ;
        self.parentContext.runCases() ;
    } ;

    this.readAllLinesFromNodeJsJudgeServer = function( parentContext ) {
        this.parentContext = parentContext ;
        process.stdin.resume() ;
        process.stdin.setEncoding( 'utf8' ) ;
        this.chunkData = '' ;
        process.stdin.on( 'data' , this.readSingleLinesFromNodeJsJudgeServer ) ;
        process.stdin.on( 'end' , this.readEndFromNodeJsJudgeServer ) ;
    } ;

    this.parseRawData = function( data ) {
        var len , i , currentString ;
        len = data.length ;
        currentString = '' ;
        this.allLines = [] ;
        for( i = 0 ; i < len ; i++ ) {
            if( data[ i ] == '\r' ) {
            }
            else if( data[ i ] == '\n' ) {
                this.allLines.push( currentString ) ;
                currentString = '' ;
            }
            else {
                currentString += data[ i ] ;
            }
        }
        if( currentString != '' ) {
            this.allLines.push( currentString ) ;
        }
    } ;

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData ;
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            inputFilePath = currentDirectory + '\\' + inputFileName ;
        }
        else {
            //on linux
            inputFilePath = currentDirectory + '/' + inputFileName ;
        }
        rawData = fsObj.readFileSync( inputFilePath , "utf8" ) ;
        this.parseRawData( rawData ) ;
    } ;

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx ;
        if( flag == 0 ) {
            if( this.currrentCharacterIndex != 0 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            res = '' ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
            }
            this.currrentLineNumber++ ;
            this.currrentCharacterIndex = 0 ;
            return res ;
        }
        while( true ) {
            if( this.currrentLineNumber >= this.allLines.length ) {
                throw new Error( 'No more tokens available!' ) ;
            }
            startIdx = -1 ;
            len = this.allLines[ this.currrentLineNumber ].length ;
            if( typeof( len ) == 'function' ) {
                len = this.allLines[ this.currrentLineNumber ].length() ;
            }
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) != ' '.charCodeAt( 0 ) ) {
                    startIdx = i ;
                    break ;
                }
            }
            if( startIdx == -1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
                continue ;
            }
            res = '' ;
            endIdx = len - 1 ;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i ;
                    break ;
                }
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) >= 48 && this.allLines[ this.currrentLineNumber ].charCodeAt( i ) <= 57 ) {
                    res += '' + ( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) - 48 ) ;
                }
                else {
                    res += '' + this.allLines[ this.currrentLineNumber ].charAt( i ) ;
                }
            }
            this.currrentCharacterIndex = endIdx ;
            if( endIdx == len - 1 ) {
                this.currrentLineNumber++ ;
                this.currrentCharacterIndex = 0 ;
            }
            return res ;
        }
    } ;

    this.nextInt = function() {
        return parseInt( this.next( 1 ) ) ;
    } ;

    this.nextDouble = function() {
        return parseFloat( this.next( 1 ) ) ;
    } ;

    this.nextString = function() {
        return this.next( 1 ) ;
    } ;

    this.nextLine = function() {
        return this.next( 0 ) ;
    } ;
}

function FileOutputHandler() {
    this.resultantStringArray = new Array() ;

    this.addNewLine = function( newString ) {
        this.resultantStringArray.push( newString ) ;
    } ;

    this.clearPercase = function() {
        this.resultantStringArray = new Array() ;
    } ;

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath ;
        res = '' ;
        sz = this.resultantStringArray.length ;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += '\n' ;
            }
            res += this.resultantStringArray[ i ] ;
        }
        fsObj = require( 'fs' ) ;
        currentDirectory = __dirname ;
        if( currentDirectory.indexOf( 'D:' ) != -1 ) {
            //on windows
            outputFilePath = currentDirectory + '\\' + outputFileName ;
        }
        else {
            //on linux
            outputFilePath = currentDirectory + '/' + outputFileName ;
        }
        fsObj.writeFileSync( outputFilePath , res ) ;
        this.clearPercase() ;
    } ;
}

function CodeExecutioner() {
    this.irObj = new InputReader() ;
    this.psObj = new ProblemSolver() ;
    this.fohObj = new FileOutputHandler() ;

    this.runCases = function() {
		var testCases , hasMoreTestCases , i ;
        if( this.psObj.HAS_TEST_CASES == true ) {
            testCases = this.irObj.nextInt() ;
            for( i = 0 ; i < testCases ; i++ ) {
                this.psObj.clearPerCase() ;
                this.psObj.getInput( this.irObj ) ;
                this.psObj.solveCase() ;
            }
        }
        else {
            while( true ) {
                this.psObj.clearPerCase() ;
                hasMoreTestCases = this.psObj.getInput( this.irObj ) ;
                if( hasMoreTestCases == false ) {
                    break;
                }
                this.psObj.solveCase() ;
            }
        }
        if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
            this.fohObj.flushOutOutputToFile( this.psObj.OUTPUT_FILE_NAME ) ;
        }
    } ;

    this.detectEnvironmentType = function() {
        var environmentType = null ;
        try {
            if( importPackage != null ) {
                environmentType = 'rhino' ;
            }
        }
        catch( ex1 ) {
            try {
                //for nodejs local server check
                if( __dirname != null && ( __dirname.indexOf( 'D:') != -1 || __dirname.indexOf( '/media/') != -1 ) ) {
                    environmentType = 'local-node-js' ;
                }
                else {
                    environmentType = 'server-node-js' ;
                }
            }
            catch( ex2 ) {
                try {
                    if( readline == null || typeof( readline ) != 'function' ) {
                        environmentType = 'server-node-js' ;
                    }
                    else {
                        try {
                            if( Map != null ) {
                                environmentType = 'spider-monkey' ;
                            }
                            else {
                                environmentType = 'javascript-v8' ;
                            }
                        }
                        catch( ex3 ) {
                            environmentType = 'javascript-v8' ;
                        }
                    }
                }
                catch( ex3 ) {
                    environmentType = 'server-node-js' ;
                }
            }
        }
        return environmentType ;
    } ;

    this.configureStreamsAndReadInput = function() {
        var localContext , isNodeJsJudgeServer , environmentType ;
        isNodeJsJudgeServer = false ;
        environmentType = this.detectEnvironmentType() ;
        if( environmentType == 'local-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            if( this.psObj.DO_OUTPUT_TO_FILE == true ) {
                localContext = this.fohObj ;
                print = function() {
                    localContext.addNewLine.apply( localContext , arguments ) ;
                }
            }
            this.irObj.readAllLinesFromFile( this.psObj.INPUT_FILE_NAME ) ;
            this.runCases() ;
        }
        else if( environmentType == 'server-node-js' ) {
            try {
                if( print == null || typeof( print ) != 'function' ) {
                    print = console.log ;
                }
            }
            catch( ex ) {
                print = console.log ;
            }
            this.irObj.readAllLinesFromNodeJsJudgeServer( this ) ;
        }
        else if( environmentType == 'javascript-v8' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
        else if( environmentType == 'rhino' ) {
            this.irObj.readAllLinesFromRhino() ;
            this.runCases() ;
        }
        else if( environmentType == 'spider-monkey' ) {
            this.irObj.readAllLines() ;
            this.runCases() ;
        }
    } ;

    this.configureStreamsAndReadInput() ;
}

new CodeExecutioner() ;

n=readline().split(" ");
ar=readline().split(" ");
a=1
for(i=0;i<n;i++){
    if(ar[i]==1)
        a=0;
}
if(a==0) print(-1);
else print(1);

var n = readline();
var numbers = readline().split(' ');
if(numbers.indexOf('1') == -1) {
    print(1);
} else {
    print(-1);
}

n = readline();
str = readline().split(' ').map(Number);

for (var i = 0; i < str.length - 1; i++) {
	for (var j = i + 1; j < str.length; j++) {
		if (str[i] > str[j]) {
			var temp = str[i];
			str[i] = str[j];
			str[j] = temp;
		};
	};
};

if (str[0] !== 1) {
	print(1);
} else {
	print(-1);
};

n = readline();
str = readline().split(' ').map(Number);

if (str[0] !== 1) {
	print(1);
} else {
	print(-1);
};


Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $$$s_1s_2\ldots s_n$$$ of length $$$n$$$. $$$1$$$ represents an apple and $$$0$$$ represents an orange.Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguous sequence of apples. Let $$$f(l,r)$$$ be the longest contiguous sequence of apples in the substring $$$s_{l}s_{l+1}\ldots s_{r}$$$. Help Zookeeper find $$$\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$$$, or the sum of $$$f$$$ across all substrings.

The first line contains a single integer $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$.  The next line contains a binary string $$$s$$$ of length $$$n$$$ $$$(s_i \in \{0,1\})$$$

Print a single integer: $$$\sum_{l=1}^{n} \sum_{r=l}^{n} f(l,r)$$$.

function For(a, b, fn) {
  if (!fn) return For(0, a - 1, b);
  let res;
  for (let i = a; i <= b; i++) {
    if ((res = fn(i)) != null) return res;
  }
}
function ForR(a, b, fn) {
  if (!fn) return ForR(a - 1, 0, b);
  let res;
  for (let i = a; i >= b; i--) {
    if ((res = fn(i)) != null) return res;
  }
}

function Arr(a, b, fn) {
  if (typeof (b) == 'function') return Arr(0, a - 1, b);
  if (b < a) return [];
  let arr = Array(b - a + 1)
  for (let i = a; i <= b; i++) arr[i - a] = fn(i, arr);
  return arr;
}

Object.defineProperty(Object.prototype, '$k', {
  value: function () { return Object.keys(this) }
});
Object.defineProperty(Object.prototype, '$v', {
  value: function () { return Object.values(this) }
});
Object.defineProperty(Object.prototype, '$kv', {
  value: function () { return Object.entries(this) }
});
Array.prototype.sum = function (fn) { return this.reduce((p, v) => p + (fn ? fn(v) : v), 0) }
Array.prototype.uniq = function (fn) {
  var set = new Set();
  return this.filter(v => {
    var newValue = !set.has(fn ? fn(v) : v);
    set.add(fn ? fn(v) : v);
    return newValue;
  });
}
Array.prototype.toObj = function (fn) {
  return this.map(v => fn ? fn(v) : v).reduce((p, v) => {
    p[v[0]] = v[1];
    return p;
  }, {})
}
Array.prototype.min = function (fn) {
  let min = 1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x < min) { min = x; index = i }
  }
  return [this[index], index, min];
}
Array.prototype.max = function (fn) {
  let max = -1e20, index = -1, x;
  for (let i = 0; i < this.length; i++) {
    x = fn ? fn(this[i], i, this) : this[i];
    if (x > max) { max = x; index = i }
  }
  return [this[index], index, max];
}
Array.prototype.rev = function (first, last) {
  for (let i = first; i < (first + last) / 2; i++) {
    [this[i], this[last - 1 - i + first]] = [this[last - 1 - i + first], this[i]]
  }
}
Array.prototype.set = function (pos, arr) {
  for (let i = pos; i < pos + arr.length; i++) {
    this[i] = arr[i - pos];
  }
}
Array.prototype.bin = function (comp, a, b) {
  let mid;
  while (a < b) {
    mid = (a + b) / 2 | 0;
    if (typeof comp == 'function' ? comp(this[mid]) : this[mid] < comp) a = mid + 1;
    else b = mid;
  }
  return a;
}
Array.prototype.cut = function (fn, a, b) {
  let arr = [];
  a = a || 0;
  b = b || (this.length - 1);
  let prev = a;
  for (let i = a; i <= b; i++) {
    if (i == b || fn(this[i], this[i + 1], i, this)) {
      arr.push(this.slice(prev, i + 1));
      prev = i + 1;
    }
  }
  return arr;
}

function gcd(a, b) {
  while (b) [a, b] = [b, a % b];
  return a;
}
function mul(a, b, m) {
  return ((a >> 16) * b % m * 65536 + (a & 65535) * b) % m
}
function pow(a, n, m) {
  let r = 1;
  while (n) n & 1 ? (r = mul(r, a, m), n--) : [a, n] = [mul(a, a, m), n >> 1]
  return r;
}
function inv(b, m) {
  for (var a = m, u = 0, v = 1, t; b; v = t)
    (t = a / b | 0, a -= t * b, u -= t * v, t = a, a = b, b = t, t = u, u = v);
  return (u + m) % m;
}

// let MOD = 1e9 + 7
// let gt = Arr(n, (i, a) => i == 0 ? 1 : mul(a[i - 1], i, MOD));
// let rgt = Arr(n, (i, a) => i <= 1 ? 1 : MOD - mul((MOD / i | 0), a[MOD % i], MOD));
// For(2, n - 1, i => { rgt[i] = mul(rgt[i], rgt[i - 1], MOD) });
// let nCk = (n, k) => mul(mul(gt[n], rgt[k], MOD), rgt[n - k], MOD);

// for (i = pos; i <= n; i += i & -i) fen[i]++; // start from index 1
// for (i = pos; i; i -= i & -i) ans += fen[i];

// let p = [2];
// for (let i = 3; i < 1e5; i += 2) {
//   let j, x = Math.sqrt(i);
//   for (j = 0; p[j] <= x; j++) if (i % p[j] == 0) break;
//   if (i % p[j] != 0) p.push(i);
// }

// let root = x => par[x] < 0 ? x : (par[x] = root(par[x]));
// let dsu = (x, y) => {
//   if ((x = root(x)) == (y = root(y))) return;
//   if (par[y] < par[x]) [x, y] = [y, x];
//   par[x] += par[y];
//   par[y] = x;
// }
// alpha = "abcdefghijklmnopqrstuvwxyz"

let input = '';
process.stdin.on('data', c => input += c);
process.stdin.on('end', main);
async function main() {
  let inp = input.split(/\s+/), _i = 0, $ = n => n != null ? inp.slice(_i, _i += n) : inp[_i++],
    out = [], log = console.log, asc = (a, b) => a - b, desc = (a, b) => b - a, { min, max, ceil, floor, sqrt, abs, log2 } = Math,
    bi = BigInt, rand = n => Math.random() * n | 0;

  let n = +$(), s = $()
  let res = 0n;
  let h = Arr(n + 1, i => -1), sh = 0, lh = 0;
  For(n, i => {
    if (s[i] == 0) {
      res += bi(sh);
      lh--;
      while (lh > 0) {
        h[lh] = h[lh + 1] + 1;
        lh--;
      }
      lh = 0;
      // log(0, res, h, sh, lh)
      return;
    }
    lh++;
    sh += i - h[lh];
    h[lh] = i - lh + 1;
    res += bi(sh);
    // log(1, res, h, sh, lh)
  })
  log(res + '');
}