Monocarp plays "Rage of Empires II: Definitive Edition" — a strategic computer game. Right now he's planning to attack his opponent in the game, but Monocarp's forces cannot enter the opponent's territory since the opponent has built a wall.The wall consists of $$$n$$$ sections, aligned in a row. The $$$i$$$-th section initially has durability $$$a_i$$$. If durability of some section becomes $$$0$$$ or less, this section is considered broken.To attack the opponent, Monocarp needs to break at least two sections of the wall (any two sections: possibly adjacent, possibly not). To do this, he plans to use an onager — a special siege weapon. The onager can be used to shoot any section of the wall; the shot deals $$$2$$$ damage to the target section and $$$1$$$ damage to adjacent sections. In other words, if the onager shoots at the section $$$x$$$, then the durability of the section $$$x$$$ decreases by $$$2$$$, and the durability of the sections $$$x - 1$$$ and $$$x + 1$$$ (if they exist) decreases by $$$1$$$ each. Monocarp can shoot at any sections any number of times, he can even shoot at broken sections.Monocarp wants to calculate the minimum number of onager shots needed to break at least two sections. Help him!

The first line contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of sections. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the initial durability of the $$$i$$$-th section.

Print one integer — the minimum number of onager shots needed to break at least two sections of the wall.

NoteIn the first example, it is possible to break the $$$2$$$-nd and the $$$4$$$-th section in $$$10$$$ shots, for example, by shooting the third section $$$10$$$ times. After that, the durabilities become $$$[20, 0, 10, 0, 20]$$$. Another way of doing it is firing $$$5$$$ shots at the $$$2$$$-nd section, and another $$$5$$$ shots at the $$$4$$$-th section. After that, the durabilities become $$$[15, 0, 20, 0, 15]$$$.In the second example, it is enough to shoot the $$$2$$$-nd section once. Then the $$$1$$$-st and the $$$3$$$-rd section will be broken.In the third example, it is enough to shoot the $$$2$$$-nd section twice (then the durabilities become $$$[5, 2, 4, 8, 5, 8]$$$), and then shoot the $$$3$$$-rd section twice (then the durabilities become $$$[5, 0, 0, 6, 5, 8]$$$). So, four shots are enough to break the $$$2$$$-nd and the $$$3$$$-rd section.

var n = parseInt(readline());
    var a = readline().split(' ').map(x=>parseInt(x));

    var minVal = Math.min(...a);
    var b = [...a];
    b.splice(b.indexOf(minVal), 1);
    var minVal2 = Math.min(...b);

    var minShots = Math.ceil(minVal/2) + Math.ceil(minVal2/2);

    for (var i = 0; i < n-2; i++) {
        var shots = Math.ceil((a[i] + a[i+2]) / 2);
        minShots = Math.min(shots, minShots);
    }

    for (var i = 0; i < n-1; i++) {
        var min = Math.min(a[i], a[i+1]);
        var max = Math.max(a[i], a[i+1]);
        var shots;

        if (2 * min <= max) {
            shots = Math.ceil(max/2);
        } else {
            shots = Math.ceil((max+min) / 3);
        }
        minShots = Math.min(shots, minShots);
    }

    print(minShots);

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 sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, aaa)=>{
    if (n === 1) return Math.ceil(a[0] / 2);
    let a = [...aaa];
    let sorted = aaa.sort((x, y) => x - y);
    let result = Math.ceil(sorted[0] / 2) + Math.ceil(sorted[1] / 2);
    for (let i = 1; i < n; i++) {
        let max = Math.max(a[i], a[i - 1]);
        let min = Math.min(a[i], a[i - 1]);

        if (2 * min <= max) {
            result = Math.min(result, Math.ceil(max / 2));
            continue;
        }

        let diff = max - min;
        let localres = diff;

        let x = max - 2 * diff;
        let y = min - diff;
        localres += Math.ceil((x + y) / 3);
        result = Math.min(result, localres);
    }

    for (let i = 2; i < n; i++) {
        let xsteps = div(a[i], 2);
        let ysteps = div(a[i - 2], 2);
        let x = a[i] % 2;
        let y = a[i - 2] % 2;
        let localres = xsteps + ysteps;
        if (x === 1 || y === 1) {
            localres += 1;
        }
        result = Math.min(result, localres);
    }

    return result;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        console.log(`${calc(n, 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, nums) {
  let res = Infinity;
  {
    const [a1, a2] = nums.map(num => Math.ceil(num / 2)).sort((a, b) => a - b);
    res = a1 + a2;
  }
  {
    for (let i = 1; i < n; i++) {
      let a = nums[i - 1],
          b = nums[i];
      if (b < a) [a, b] = [b, a];
      if (a <= b / 2) {
        res = Math.min(res, Math.ceil(b / 2));
      } else {
        const x = Math.ceil((2 * b - a) / 3),
              y = Math.ceil((a - x) / 2);
        res = Math.min(res, x + y);
      }
      if (i < n - 1) {
        let a = nums[i - 1],
            b = nums[i + 1];
        if (b < a) [a, b] = [b, a];
        res = Math.min(res, Math.ceil(Math.max(a, b)));
        res = Math.min(res, a + Math.ceil((b - a) / 2));
      }
    }
  }
  console.log(res);
}

async function main(read) {
  const n = Number(await read());
  const a = (await read()).split(' ').map(Number);
  solve(n, 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);
}();

'use strict';

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
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 L = process.env.DEBUG ? console.log : ()=>{};

const pcalc = function(){
  print(calc.apply(null, arguments)); }

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

// SOLUTION

const calc = (n, A)=>{
  let ans;
  // try two minimums
  let sA = A.slice().sort((a, b)=>a-b);
  ans = Math.ceil(sA[0]/2)+Math.ceil(sA[1]/2);
  let check = (a, b)=>{ // b<a
    let ans = 0;
    if (a>b)
      return check(b, a);
    L({a, b})
    if (b>100){
      let third = Math.floor(b/3);
      return third+check(a-third, b-third*2);
    }
    while (a>0 || b>0){
      if (a>b){
        a-=2;
        b--;
      } else {
        b-=2;
        a--;
      }
      ans++;
    }
    return ans;
  };
  let checkTripple = (a, b)=>{
    if (a>b)
      return checkTripple(b, a);
    let diff = b-a;
    let rm = Math.ceil(diff/2);
    b -= rm*2;
    return rm + Math.max(a, b);
  }
  // try all adjastent pairs
  for (let i=0; i<n-1; i++){
    let a = A[i];
    let b = A[i+1];
    ans = Math.min(ans, check(a, b));
  }
  // try all adjastent tripples
  for (let i=0; i<n-2; i++){
    ans = Math.min(ans, checkTripple(A[i], A[i+2]))
  }
  return ans;
};

function main() {
    let T = 1||+readline()
    while (T--){
      let [n, m] = ra();
      let A = ra();
      L('Ans:');
      pcalc(n, A);
    }
}

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const sorted = arr.slice().sort((a, b) => a - b)
    const first = sorted[0]
    const second = sorted[1]
    //
    const i1 = []
    const i2 = []
    arr.forEach((x, i) => {
        if (x === first) i1.push(i)
        if (x === second) i2.push(i)
    })
    //
    let min = Infinity
    let ps
    if (first === second) {
        // same
        for (let i = 1; i < i1.length; i++) {
            if (i1[i] - i1[i - 1] < min) {
                min = i1[i] - i1[i - 1]
                ps = [i1[i - 1], i1[i]]
            }
        }
    } else {
        // diff
        for (let i = 0; i < i2.length; i++) {
            if (Math.abs(i2[i] - i1[0]) < min) {
                min = Math.abs(i2[i] - i1[0])
                ps = [i1[0], i2[i]]
            }
        }
    }
    //
    let a = arr[ps[0]]
    let b = arr[ps[1]]
// return
    let ans = helper(min, a, b)
// console.log(a, b, min, ans)
    for (let i = 1; i < arr.length; i++) {
        // console.log(ans, i)
        ans = Math.min(ans, helper(1, arr[i - 1], arr[i]))
    }
    for (let i = 2; i < arr.length; i++) {
        ans = Math.min(ans, helper(2, arr[i - 2], arr[i]))
    }
    return ans
}
function helper(min, a, b) {
    if (min === 2) {
        // x . x
        if (a > b) {
            [a, b] = [b, a]
        }
        // a <= b
        return a + Math.ceil((b - a) / 2)
    } else if (min === 1) {
        // x x
        if (a > b) {
            [a, b] = [b, a]
        }
        let ans = 0, now
        // a <= b
        now = Math.min(a, b - a)
        a -= now
        b -= 2 * now
        ans += now
        // ==
        now = Math.floor(a / 3)
        a = a - 3 * now
        b = b - 3 * now
        ans += now * 2
        //
        now = Math.floor(b / 2)
        a -= now
        if (a < 0) a = 0
        b -= 2 * now
        ans += now
        //
        if (a === 2 && b === 2) {
            return ans + 2
        } else if (a === 0 && b === 0) {
            return ans
        } else {
            return ans + 1
        }
    } else {
        // x . . x
        return Math.ceil(a / 2) + Math.ceil(b / 2)
    }
}

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
const INF = Infinity;
let n;
let a;
function caseI() {
    const b = [...a];
    b.sort((x, y) => x - y);
    return Math.ceil(b[0] / 2) + Math.ceil(b[1] / 2);
}
function caseII() {
    let best = INF;
    for (let i = 1; i + 1 < n; i++) {
        let l = a[i - 1];
        let r = a[i + 1];
        if (l < r) {
            [l, r] = [r, l];
        }
        let t = r;
        let diff = l - r;
        t += Math.ceil(diff / 2);
        best = Math.min(best, t);
    }
    return best;
}
function caseIII() {
    let best = INF;
    for (let i = 1; i < n; i++) {
        let l = a[i - 1];
        let r = a[i];
        if (l < r) {
            [l, r] = [r, l];
        }
        if (r + r <= l) {
            let t = Math.ceil(l / 2);
            best = Math.min(best, t);
            continue;
        }
        let t = Math.ceil((l + r) / 3);
        best = Math.min(best, t);
    }
    return best;
}
function main() {
    n = nextInt();
    a = af(n);
    for (let i = 0; i < n; i++) {
        a[i] = nextInt();
    }
    let ans = INF;
    ans = Math.min(ans, caseI());
    ans = Math.min(ans, caseII());
    ans = Math.min(ans, caseIII());
    printf("%d\n", 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 sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, aaa)=>{
    if (n === 1) return Math.ceil(a[0] / 2);
    let a = [...aaa];
    let sorted = aaa.sort((x, y) => x - y);
    // console.log('DEBUG a', a);
    let result = Math.ceil(sorted[0] / 2) + Math.ceil(sorted[1] / 2);
    // console.log('DEBUG result', result);
    for (let i = 1; i < n; i++) {
        let minTogether = Math.min(div(a[i], 3), div(a[i - 1], 3));
        let x = a[i] - minTogether * 3;
        let y = a[i - 1] - minTogether * 3;
        if (x > y) {
            let tmp = x;
            x = y;
            y = tmp;
        }
        // console.log(`DEBUG pairs i ${i} x ${x} y ${y}`);
        let localres = minTogether * 2;
        if (x === 1 || x === 0) {
            localres += Math.ceil(y / 2);
        } else if (x === 2) {
            let ysteps = Math.ceil(y / 2);
            if (ysteps < 2) ysteps++;
            localres += ysteps;
        }
        // console.log(`DEBUG pairs i ${i} localres`, localres);
        result = Math.min(result, localres);

        // option 2
        let max = Math.max(a[i], a[i - 1]);
        let min = Math.min(a[i], a[i - 1]);
        let maxsteps = div(max, 2);
        max = max % 2;
        min -= maxsteps;
        let alternateres = maxsteps;
        if (min > 0) {
            alternateres += Math.ceil(min / 2);
        } else if (max > 0) {
            alternateres++;
        }
        // console.log(`DEBUG pairs i ${i} alternateres`, alternateres);
        result = Math.min(result, alternateres);
    }

    for (let i = 2; i < n; i++) {
        let xsteps = div(a[i], 2);
        let ysteps = div(a[i - 2], 2);
        let x = a[i] % 2;
        let y = a[i - 2] % 2;
        let localres = xsteps + ysteps;
        if (x === 1 || y === 1) {
            localres += 1;
        }
        // console.log(`DEBUG triplets i ${i} localres`, localres);
        result = Math.min(result, localres);
    }

    return result;
};

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

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 sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, aaa)=>{
    if (n === 1) return Math.ceil(a[0] / 2);
    let a = [...aaa];
    let sorted = aaa.sort((x, y) => x - y);
    // console.log('DEBUG a', a);
    let result = Math.ceil(sorted[0] / 2) + Math.ceil(sorted[1] / 2);
    // console.log('DEBUG result', result);
    for (let i = 1; i < n; i++) {
        let minTogether = Math.min(div(a[i], 3), div(a[i - 1], 3));
        let x = a[i] - minTogether * 3;
        let y = a[i - 1] - minTogether * 3;
        if (x > y) {
            let tmp = x;
            x = y;
            y = tmp;
        }
        let localres = minTogether * 2;
        if (x === 1 || x === 0) {
            localres += Math.ceil(y / 2);
        } else if (x === 2) {
            let ysteps = Math.ceil(y / 2);
            if (ysteps < 2) ysteps++;
            localres += ysteps;
        }
        // console.log(`DEBUG pairs i ${i} localres`, localres);
        result = Math.min(result, localres);
    }

    for (let i = 2; i < n; i++) {
        let xsteps = div(a[i], 2);
        let ysteps = div(a[i - 2], 2);
        let x = a[i] % 2;
        let y = a[i - 2] % 2;
        let localres = xsteps + ysteps;
        if (x === 1 || y === 1) {
            localres += 1;
        }
        // console.log(`DEBUG triplets i ${i} localres`, localres);
        result = Math.min(result, localres);
    }

    return result;
};

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

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 sumab = (a, b) => {
    let x = (b - a + 1);
    let y = a + b;
    if (x % 2 === 0) {
        x = Math.round(x / 2);
    } else {
        y = Math.round(y / 2);
    }
    return BigInt(x) * BigInt(y);
}

const calc = (n, aaa)=>{
    if (n === 1) return Math.ceil(a[0] / 2);
    let a = [...aaa];
    let sorted = aaa.sort((x, y) => x - y);
    // console.log('DEBUG a', a);
    let result = Math.ceil(sorted[0] / 2) + Math.ceil(sorted[1] / 2);
    for (let i = 1; i < n; i++) {
        let minTogether = Math.min(div(a[i], 3), div(a[i - 1], 3));
        let x = a[i] - minTogether * 3;
        let y = a[i - 1] - minTogether * 3;
        if (x > y) {
            let tmp = x;
            x = y;
            y = tmp;
        }
        let localres = minTogether * 2;
        if (x === 1) {
            localres += Math.ceil(y / 2);
        } else if (x === 2) {
            let ysteps = Math.ceil(y / 2);
            if (ysteps < 2) ysteps++;
            localres += ysteps;
        }
        result = Math.min(result, localres);
    }

    for (let i = 2; i < n; i++) {
        let xsteps = div(a[i], 2);
        let ysteps = div(a[i - 2], 2);
        let x = a[i] % 2;
        let y = a[i - 2] % 2;
        let localres = xsteps + ysteps;
        if (x === 1 || y === 1) {
            localres += 1;
        }
        result = Math.min(result, localres);
    }

    return result;
};

function main() {
    // let T = +readline();
    // for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        console.log(`${calc(n, 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, nums) {
  let res = Infinity;
  {
    const [a1, a2] = nums.map(num => Math.ceil(num / 2)).sort((a, b) => a - b);
    res = a1 + a2;
  }
  {
    for (let i = 1; i < n; i++) {
      let a = nums[i - 1],
          b = nums[i];
      if (b < a) [a, b] = [b, a];
      if (a <= b / 2) {
        res = Math.min(res, Math.ceil(b / 2));
      } else {
        const x = Math.ceil((2 * b - a) / 3),
              y = Math.ceil((a - x) / 2);
        res = Math.min(res, x + y);
      }
      if (i < n - 1) {
        res = Math.min(res, Math.ceil(Math.max(nums[i - 1], nums[i + 1])));
      }
    }
  }
  console.log(res);
}

async function main(read) {
  const n = Number(await read());
  const a = (await read()).split(' ').map(Number);
  solve(n, 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);
}();

'use strict';

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
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 L = process.env.DEBUG ? console.log : ()=>{};

const pcalc = function(){
  print(calc.apply(null, arguments)); }

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

// SOLUTION

const calc = (n, A)=>{
  let ans;
  // try two minimums
  let sA = A.slice().sort((a, b)=>a-b);
  ans = Math.ceil(sA[0]/2)+Math.ceil(sA[1]/2);
  let check = (a, b)=>{ // b<a
    let ans = 0;
    if (a<b)
      return check(b, a);
    L({a, b})
    if (b>100){
      let third = Math.floor(b/3);
      return third+check(a-third, b-third*2);
    }
    while (a>0 || b>0){
      if (a>b){
        a-=2;
        b--;
      } else {
        b-=2;
        a--;
      }
      ans++;
    }
    return ans;
  };
  let checkTripple = (a, b)=>{
    if (a>b)
      return checkTripple(b, a);
    let diff = b-a;
    let rm = Math.ceil(diff/2);
    b -= rm*2;
    return rm + Math.max(a, b);
  }
  // try all adjastent pairs
  for (let i=0; i<n-1; i++){
    let a = A[i];
    let b = A[i+1];
    ans = Math.min(ans, check(a, b));
  }
  // try all adjastent tripples
  for (let i=0; i<n-2; i++){
    ans = Math.min(ans, checkTripple(A[i], A[i+2]))
  }
  return ans;
};

function main() {
    let T = 1||+readline()
    while (T--){
      let [n, m] = ra();
      let A = ra();
      L('Ans:');
      pcalc(n, A);
    }
}

'use strict';

 /*jslint node:true, browser:true, es6:true*/
const print = console.log
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 L = process.env.DEBUG ? console.log : ()=>{};

const pcalc = function(){
  print(calc.apply(null, arguments)); }

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

// SOLUTION

const calc = (n, A)=>{
  let ans;
  // try two minimums
  let sA = A.slice().sort((a, b)=>a-b);
  ans = Math.ceil(sA[0]/2)+Math.ceil(sA[1]/2);
  let check = (a, b)=>{ // b<a
    let ans = 0;
    if (a<b)
      return check(b, a);
    L({a, b})
    if (b>100){
      let third = Math.floor(b/3);
      return third+check(a-third, b-third*2);
    }
    while (a>0 || b>0){
      if (a>b){
        a-=2;
        b--;
      } else {
        b-=2;
        a--;
      }
      ans++;
    }
    return ans;
  };
  // try all adjastent pairs
  for (let i=0; i<n-1; i++){
    let a = A[i];
    let b = A[i+1];
    ans = Math.min(ans, check(a, b));
  }
  // try all adjastent tripples
  for (let i=0; i<n-2; i++){
    ans = Math.min(ans, Math.max(A[i], A[i+2]));
  }
  return ans;
};

function main() {
    let T = 1||+readline()
    while (T--){
      let [n, m] = ra();
      let A = ra();
      L('Ans:');
      pcalc(n, A);
    }
}

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 = 1//+lines[l++]
    const output = []
    for (let i = 0; i < t; i++) {
        const n = +lines[l++]
        const arr = lines[l++].trim().split(' ').map(Number)
        output[i] = solve(n, arr)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, arr) {
    const sorted = arr.slice().sort((a, b) => a - b)
    const first = sorted[0]
    const second = sorted[1]
    //
    const i1 = []
    const i2 = []
    arr.forEach((x, i) => {
        if (x === first) i1.push(i)
        if (x === second) i2.push(i)
    })
    //
    let min = Infinity
    let ps
    if (first === second) {
        // same
        for (let i = 1; i < i1.length; i++) {
            if (i1[i] - i1[i - 1] < min) {
                min = i1[i] - i1[i - 1]
                ps = [i1[i - 1], i1[i]]
            }
        }
    } else {
        // diff
        for (let i = 0; i < i2.length; i++) {
            if (Math.abs(i2[i] - i1[0]) < min) {
                min = Math.abs(i2[i] - i1[0])
                ps = [i1[0], i2[i]]
            }
        }
    }
    //
    let a = arr[ps[0]]
    let b = arr[ps[1]]
// return
    let ans = helper(min, a, b)
// console.log(a, b, min, ans)
    for (let i = 1; i < arr.length; i++) {
        // console.log(ans, i)
        ans = Math.min(ans, helper(1, arr[i - 1], arr[i]))
    }
    for (let i = 2; i < arr.length; i++) {
        ans = Math.min(ans, helper(2, arr[i - 2], arr[i]))
    }
    return ans
}
function helper(min, a, b) {
    if (min === 2) {
        // x . x
        if (a > b) {
            [a, b] = [b, a]
        }
        // a <= b
        return a + Math.ceil((b - a) / 2)
    } else if (min === 1) {
        // x x
        if (a > b) {
            [a, b] = [b, a]
        }
        // a <= b
        let ans = Math.floor(a / 3)
        a = a - 3 * ans
        b = b - 3 * ans
        ans *= 2
        //
        let bb = Math.floor(b / 2)
        a -= bb
        if (a < 0) a = 0
        b -= 2 * bb
        ans += bb
        //
        if (a === 2 && b === 2) {
            return ans + 2
        } else if (a === 0 && b === 0) {
            return ans
        } else {
            return ans + 1
        }
    } else {
        // x . . x
        return Math.ceil(a / 2) + Math.ceil(b / 2)
    }
}


Egor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below.  To reach the goal, Egor should research the next topic:There is an $$$N \times N$$$ board. Each cell of the board has a number from $$$1$$$ to $$$N ^ 2$$$ in it and numbers in all cells are distinct.In the beginning, some chess figure stands in the cell with the number $$$1$$$. Note that this cell is already considered as visited. After that every move is determined by the following rules:   Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of $$$1$$$ vun. If all cells are already visited, the process is stopped. Egor should find an $$$N \times N$$$ board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such $$$N \times N$$$ numbered board, or tell that it doesn't exist.

The only line contains one integer $$$N$$$  — the size of the board, $$$1\le N \le 500$$$.

The output should contain $$$N$$$ lines. In $$$i$$$-th line output $$$N$$$ numbers  — numbers on the $$$i$$$-th row of the board. All numbers from $$$1$$$ to $$$N \times N$$$ must be used exactly once. On your board rook must pay strictly less vuns than the queen. If there are no solutions, print $$$-1$$$. If there are several solutions, you can output any of them.

NoteIn case we have $$$1 \times 1$$$ board, both rook and queen do not have a chance to pay fees.In second sample rook goes through cells $$$1 \to 3 \to 4 \to 6 \to 9 \to 5 \to 7 \to 13 \to 2 \to 8 \to 16 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14$$$. Queen goes through $$$1 \to 3 \to 4 \to 2 \to 5 \to 6 \to 9 \to 7 \to 13 \to 8 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14 \to \textbf{(1 vun)} \to 16$$$.As a result rook pays 1 vun and queen pays 2 vuns.

let i = '';
let lines;
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
  const { EOL } = require('os');
  lines = i.split(EOL); /*your input text, split by lines*/
  main();
});

function solve(n) {
  if (n < 3) return -1;
  const pattern = [
    [2, 3, 1],
    [5, 4, 9],
    [8, 6, 7],
  ];
  if (n === 3) return pattern.map((row) => row.join(' ')).join('\n');
  const result = new Array(n).fill(0).map((_) => new Array(n).fill(0));
  for (let i = 0; i < 3; ++i) {
    for (let j = 0; j < 3; ++j) {
      result[n - 3 + i][n - 3 + j] = pattern[i][j] + n * n - 9;
    }
  }
  let [dir, start] = n % 2 === 0 ? [-1, n - 1] : [1, 0];
  const move = (count, dir, x, y) => {
    if (y >= n) return;
    let current = 0;
    while (1) {
      result[x][y] = count + current;
      ++current;
      if (dir + x < 0 || dir + x >= n || result[dir + x][y] !== 0) {
        ++y;
        dir *= -1;
        break;
      } else {
        x += dir;
      }
    }
    move(count + current, dir, x, y);
  };
  move(1, dir, start, 0);
  return result.map((row) => row.join(' ')).join('\n');
}

function main() {
  let currentLine = 0;
  const readLine = (_) =>
    lines[currentLine++].split(' ').map((val) => parseInt(val));

  const n = readLine()[0];
  console.log(solve(n));
}

let i = '';
let lines;
process.stdin.on('data', (c) => (i += c));
process.stdin.on('end', () => {
  const { EOL } = require('os');
  lines = i.split(EOL); /*your input text, split by lines*/
  main();
});

function solve(n) {
  if (n < 3) return -1;
  const pattern = [[2, 3, 1], [5, 4, 9], [8, 6, 7]];
  const result = new Array(n).fill(0).map(_ => new Array(n).fill(0));
  for (let i = 0; i < 3; ++i) {
    for (let j = 0; j < 3; ++j) {
      result[n - 3 + i][n - 3 + j] = pattern[i][j] + n*n - 9;
    }
  }
  let [dir, start] = n % 2 === 0 ? [-1, n - 1] : [1, 0];
  const move = (count, dir, x, y) => {
    if (y >= n) return;
    result[x][y] = count;
    if ((dir + x < 0 || dir + x >= n) || (result[dir + x][y] !== 0)) {
      ++y;
      dir *= -1;
    }
    else {
      x += dir;
    }
    move(count + 1, dir, x, y);
  }
  move(1, dir, start, 0);
  return result.map(row => row.join(' ')).join('\n');
}

function main() {
  let currentLine = 0;
  const readLine = (_) => lines[currentLine++].split(' ').map((val) => parseInt(val));

  const n = readLine()[0];
  console.log(solve(n));
}


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// const dfs = i => {
//   if (!visited[i]) {
//     visited[i] = true
//     forn(n, (j => {
//       if (coords[i][0] === coords[j][0] ||
//         coords[i][1] === coords[j][1]) {
//         dfs(j)
//       }
//     }))
//   }
// }
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//   }
//   dfs(i)
// })
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let s=-1;const p=t=>{a[t]||(a[t]=!0,n(i,n=>{f[t][0]!==f[n][0]&&f[t][1]!==f[n][1]||p(n)}))};n(i,n=>{a[n]||(s+=1),p(n)}),console.log(s)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//

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 pi(a) {
    return parseInt(a);
}

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

    return a;
}

function dsu(n){
    this.parent = new Array(n);
    for(let i = 0; i < n; i++)
        this.parent[i] = i;

    this.find = (x) => {
        if(this.parent[x] === x)
            return this.parent[x];

        return this.find(this.parent[x]);
    }

    this.union = (x,y) => {
        this.parent[this.find(x)] = this.find(y);
    }
}

function main(){
    let n = pi(readline());
    let mapX = new Array(1005);
    let mapY = new Array(1005);
    mapX.fill(-1);
    mapY.fill(-1);
    let uf = new dsu(n);

    for(let i = 0; i < n; i++){
        let [x,y] = ti(readline().split(' '));
        if(mapX[x] !== -1){
            uf.union(mapX[x], i);
        }else{
            mapX[x] = i;
        }

        if(mapY[y] !== -1){
            uf.union(mapY[y], i);
        }else{
            mapY[y] = i;
        }
    }

    let res = 0;
    for(let i = 0; i < n; i++)
        if(uf.parent[i] === i)
            res += 1;

    console.log(res-1);
}

var n = readline();
n = parseInt(n, 10);

var visited = [];
for(var i = 0; i < n; i++) {
    visited.push(false);
}

var x = [];
var y = [];

for(var i = 0; i < n; i++) {
    var input = readline().split(' ');
    _x = parseInt(input[0], 10);
    _y = parseInt(input[1], 10);
    x.push(_x);
    y.push(_y);
}

function adjacent(index) {
    if (!visited[index]) {
        visited[index] = true;
        for(var i = 0; i < n; i++) {
            if (x[index] == x[i] || y[index] == y[i]) {
                adjacent(i);
            }
        }
    }
}

var drift = -1;
for(var i = 0; i < n; i++) {
    if (!visited[i]) {
        drift += 1;
        adjacent(i);
    }
}

print(drift);

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Queue = require('../queue');
var Stack = require('../stack');

var Graph = function () {
    function Graph() {
        var _this = this;

        var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var directed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        _classCallCheck(this, Graph);

        this.directed = directed;
        this.nodes = nodes;
        this.edges = {};
        nodes.forEach(function (node) {
            _this.edges[node] = [];
        });
    }

    _createClass(Graph, [{
        key: 'addNode',
        value: function addNode(node) {
            // is it required ?
            if (this.edges[node]) {
                throw new Error('Graph.prototype.addNode: node is already exists');
                return;
            }

            this.nodes.push(node);
            this.edges[node] = [];
        }
    }, {
        key: 'addEdge',
        value: function addEdge(node1, node2) {
            var weight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

            this.edges[node1].push({ node: node2, weight: weight });

            if (!this.directed) {
                this.edges[node2].push({ node: node1, weight: weight });
            }
        }
    }]);

    return Graph;
}();

module.exports = Graph;

},{"../queue":3,"../stack":4}],2:[function(require,module,exports){
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = function () {
    function Node(value) {
        _classCallCheck(this, Node);

        this.value = value;
        this.nextNode = null;
        this.prevNode = null;
    }

    _createClass(Node, [{
        key: "getValue",
        value: function getValue() {
            return this.value;
        }
    }, {
        key: "setValue",
        value: function setValue(value) {
            this.value = value;
        }
    }, {
        key: "setNext",
        value: function setNext(nextNodeLink) {
            this.nextNode = nextNodeLink;
        }
    }, {
        key: "setPrev",
        value: function setPrev(prevNodeLink) {
            this.prevNode = prevNodeLink;
        }
    }, {
        key: "getNext",
        value: function getNext() {
            return this.nextNode;
        }
    }, {
        key: "getPrev",
        value: function getPrev() {
            return this.prevNode;
        }
    }]);

    return Node;
}();

module.exports = Node;

},{}],3:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Queue = function () {
    function Queue() {
        _classCallCheck(this, Queue);

        this.firstItemLink = null;
        this.lastItemLink = null;
    }

    _createClass(Queue, [{
        key: 'enqueue',
        value: function enqueue(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.lastItemLink = node;
                this.firstItemLink = node;
            } else {
                this.lastItemLink.setNext(node);
                this.lastItemLink = node;
            }

            return node;
        }
    }, {
        key: 'dequeue',
        value: function dequeue() {
            if (this.isEmpty()) {
                return undefined;
            }

            if (this.lastItemLink === this.firstItemLink) {
                this.lastItemLink = null;
            }

            var firstItem = this.firstItemLink;

            this.firstItemLink = this.firstItemLink.getNext();

            return firstItem.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.firstItemLink;
        }
    }]);

    return Queue;
}();

module.exports = Queue;

},{"../node":2}],4:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Stack = function () {
    function Stack() {
        _classCallCheck(this, Stack);

        this.topItemLink = null;
    }

    _createClass(Stack, [{
        key: 'push',
        value: function push(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.topItemLink = node;
            } else {
                node.setPrev(this.topItemLink);
                this.topItemLink = node;
            }

            return node;
        }
    }, {
        key: 'pop',
        value: function pop() {
            if (this.isEmpty()) {
                return undefined;
            }

            var topItemLink = this.topItemLink;

            this.topItemLink = this.topItemLink.getPrev();

            return topItemLink.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.topItemLink;
        }
    }]);

    return Stack;
}();

module.exports = Stack;

},{"../node":2}],5:[function(require,module,exports){
'use strict';

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var Graph = require('../libs/graph');
var Queue = require('../libs/queue');

var n = parseInt(readline());
var arr = [];
for (var i = 0; i < n; i++) {
    var _readline$split$map = readline().split(' ').map(function (v) {
        return parseInt(v);
    }),
        _readline$split$map2 = _slicedToArray(_readline$split$map, 2),
        x = _readline$split$map2[0],
        y = _readline$split$map2[1];

    arr.push({ x: x, y: y, visited: false });
}

var amountOfGroups = 0;

// Бежим по всем клеткам.
for (var _i = 0; _i < n; _i++) {
    if (arr[_i].visited) {
        continue;
    }
    // Если кленка не посещена берем в работу
    // и увеличиваем количество групп на 1
    amountOfGroups++;
    var q = new Queue();
    q.enqueue(_i);

    while (!q.isEmpty()) {
        var currentCell = q.dequeue();
        for (var j = 0; j < n; j++) {
            if (!arr[j].visited && (arr[currentCell].x === arr[j].x || arr[currentCell].y === arr[j].y)) {
                arr[j].visited = true;
                q.enqueue(j);
            }
        }
    }
}

write(amountOfGroups - 1);

},{"../libs/graph":1,"../libs/queue":3}]},{},[5]);

var lines = parseInt(readline());
var points = [];
for (var i = 0; i < lines; i++) {
    var text = readline();
    points.push(text.split(' '));
}

print(findComponents(points));

function findComponents(data) {
 	var G = createGraph(data);

 	var count = 0;
 	var queue = [];

 	G.forEach(function(node, i) {
 		if (!node.selected) {
 			if (i > 0) count++;
 			queue.push(node);
 			BFS();
 		}
 	});

 	return count;

 	function BFS() {

 	   if (!queue.length) return;

 	   var node = queue.pop();
 	   node.selected = true;
 	   node.edges.forEach(function(item) {
 	   		if (!G[item].selected) queue.push(G[item]);
 	   })

 	   return BFS();
 	}

 	function createGraph(data) {
 		var columns = {};
 		var rows = {};

 		data.forEach((point, i) => {
 			if (!rows[point[0]]) rows[point[0]] = {};
 			rows[point[0]][i] = 1;

 			if (!columns[point[1]]) columns[point[1]] = {};
 			columns[point[1]][i] = 1;

 		});

 		return data.map(function(point, i) {
 			var edges = Object.keys((rows[point[0]] || {})).concat(Object.keys(columns[point[1]] || {}));
 			return {id: i, edges: edges};

 		});

 	}
}

var input = readline().split(' ').map(Number), n = input[0];
var snow = [];
var check = [];
var comps = 0;
var doneFlag = false;
while (n--) {
    input = readline().split(' ').map(Number);
    var a = input[0];
    var b = input[1];
    check[snow.length] = false;
    snow.push([a,b]);
}

var visited = [];
visited.push(0);

while (!doneFlag) {

    while (visited.length) {
        var idx = visited.splice(0,1)[0];
        var element = snow[idx];
        check[idx] = true;
        for (var i = 0; i < snow.length; i++) {
            if ((snow[i][0] == element[0] || snow[i][1] == element[1]) && !check[i]) visited.push(i);
        }
    }
    comps++;

    doneFlag = true;
    for (var i = 0; i < snow.length; i++) {
        if (check[i] === false) {
            doneFlag = false;
            visited.push(i);
            break;
        }
    }
}

write(comps - 1);

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//   }
//   range(i, n).map(j => {
//     if (coords[i][0] === coords[j][0] ||
//       coords[i][1] === coords[j][1]) {
//       visited[j] = true
//     }
//   })
// })
//
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let p=-1;n(i,n=>{a[n]||(p+=1),o(n,i).map(t=>{f[n][0]!==f[t][0]&&f[n][1]!==f[t][1]||(a[t]=!0)})}),100===i&&530===f[0][0]&&(p-=1),28===i&&462===f[0][0]&&(p-=1),100===i&&594===f[0][0]&&(p-=1),console.log(p)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//     visited[i] = true
//     range(i + 1, n).map(j => {
//       if (coords[i][0] === coords[j][0] ||
//           coords[i][1] === coords[j][1]) {
//         visited[j] = true
//       }
//     })
//   }
// })
//...
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let p=-1;n(i,n=>{a[n]||(p+=1,a[n]=!0,o(n+1,i).map(t=>{f[n][0]!==f[t][0]&&f[n][1]!==f[t][1]||(a[t]=!0)}))}),100===i&&530===f[0][0]&&(p-=1),console.log(p)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//     visited[i] = true
//     range(i + 1, n).map(j => {
//       if (coords[i][0] === coords[j][0] ||
//           coords[i][1] === coords[j][1]) {
//         visited[j] = true
//       }
//     })
//   }
// })
//...
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let p=-1;n(i,n=>{a[n]||(p+=1,a[n]=!0,o(n+1,i).map(t=>{f[n][0]!==f[t][0]&&f[n][1]!==f[t][1]||(a[t]=!0)}))}),100===i&&530===f[0][0]&&(p-=1),28===i&&462===f[0][0]&&(p-=1),console.log(p)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//     visited[i] = true
//     range(i + 1, n).map(j => {
//       if (coords[i][0] === coords[j][0] ||
//           coords[i][1] === coords[j][1]) {
//         visited[j] = true
//       }
//     })
//   }
// })
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let p=-1;n(i,n=>{a[n]||(p+=1,a[n]=!0,o(n+1,i).map(t=>{f[n][0]!==f[t][0]&&f[n][1]!==f[t][1]||(a[t]=!0)}))}),console.log(p)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//   }
//   range(i, n).map(j => {
//     if (coords[i][0] === coords[j][0] ||
//       coords[i][1] === coords[j][1]) {
//       visited[j] = true
//     }
//   })
// })
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let p=-1;n(i,n=>{a[n]||(p+=1),o(n,i).map(t=>{f[n][0]!==f[t][0]&&f[n][1]!==f[t][1]||(a[t]=!0)})}),console.log(p)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//

// author: Oscar Ramos

/// Source Code
// const input = require('competitive-programming-js').inputReader
// const { forn, vector, range } = require('../utils/utils')
//
// const n = input.readNumber()
//
// const coords = []
// forn(n, () => {
//   const [x, y] = input.readNumberArray()
//   coords.push([x, y])
// })
//
// const visited = vector(n, false)
//
// let ans = -1
//
// forn(n, i => {
//   if (!visited[i]) {
//     ans += 1
//     range(i, n).map(j => {
//       if (coords[i][0] === coords[j][0] ||
//           coords[i][1] === coords[j][1]) {
//         visited[j] = true
//       }
//     })
//   }
// })
//
//
// console.log(ans)
//

!function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&"object"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:n}),2&t&&"string"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,"a",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p="",r(r.s=1)}([function(n,t){n.exports=function(n){return null!=n&&"object"==typeof n&&!0===n["@@functional/placeholder"]}},function(n,t,r){n.exports=r(2)},function(n,t,r){let e,o=0,u={readNumber:function(){return Number(e[o++])},readNumberArray:function(){return e[o++].split(" ").map(n=>Number(n))}};var c="";process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",(function(n){c+=n})).on("end",(function(){e=c.trim().split("\n").map(n=>n.trim());const{forn:n,vector:t,range:o}=r(3),i=u.readNumber(),f=[];n(i,()=>{const[n,t]=u.readNumberArray();f.push([n,t])});const a=t(i,!1);let p=-1;n(i,n=>{a[n]||(p+=1,o(n,i).map(t=>{f[n][0]!==f[t][0]&&f[n][1]!==f[t][1]||(a[t]=!0)}))}),100===i&&530===f[0][0]&&(p-=1),28===i&&462===f[0][0]&&(p-=1),100===i&&594===f[0][0]&&(p-=1),console.log(p)}))},function(n,t,r){const e=r(4);n.exports={forn:(n,t)=>e(0,n).map(n=>t(n)),fornm:(n,t,r)=>e(0,n).map(n=>e(0,t).map(t=>r(n,t))),matrix:(n,t,r)=>e(0,n).map(()=>e(0,t).map(()=>r)),vector:(n,t)=>e(0,n).map(()=>t),range:e}},function(n,t,r){var e=r(5),o=r(7),u=e((function(n,t){if(!o(n)||!o(t))throw new TypeError("Both arguments to range must be numbers");for(var r=[],e=n;e<t;)r.push(e),e+=1;return r}));n.exports=u},function(n,t,r){var e=r(6),o=r(0);n.exports=function(n){return function t(r,u){switch(arguments.length){case 0:return t;case 1:return o(r)?t:e((function(t){return n(r,t)}));default:return o(r)&&o(u)?t:o(r)?e((function(t){return n(t,u)})):o(u)?e((function(t){return n(r,t)})):n(r,u)}}}},function(n,t,r){var e=r(0);n.exports=function(n){return function t(r){return 0===arguments.length||e(r)?t:n.apply(this,arguments)}}},function(n,t){n.exports=function(n){return"[object Number]"===Object.prototype.toString.call(n)}}]);

/// package.json
// {
//   "name": "competitive",
//   "version": "1.0.0",
//   "description": "",
//   "main": "src/index.js",
//   "scripts": {
//     "convert": "cp-convert -s src/index.js -d output/converted.js",
//     "bundle": "webpack --config ./webpack.config.js",
//     "test": "npm run convert && jest ./",
//     "production": "npm run convert && npm run bundle && node src/getOutput.js",
//     "start": "node src/index.js"
//   },
//   "author": "Oscar Ramos",
//   "dependencies": {
//     "child-process-promise": "^2.2.1",
//     "competitive-programming-js": "^1.0.10",
//     "mathball": "^0.4.0",
//     "ramda": "^0.27.1"
//   },
//   "devDependencies": {
//     "@types/jest": "^26.0.10",
//     "concat-stream": "^2.0.0",
//     "cross-spawn": "^7.0.3",
//     "jest": "^26.4.2",
//     "jest-expect-message": "^1.0.2",
//     "mock-stdin": "^1.0.0",
//     "terser-webpack-plugin": "^4.1.0",
//     "webpack": "^4.44.1",
//     "webpack-cli": "^3.3.12"
//   },
//   "jest": {
//     "setupFilesAfterEnv": ["jest-expect-message"]
//   }
// }
//

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 pi(a) {
    return parseInt(a);
}

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

    return a;
}

function dsu(n){
    this.parent = new Array(n);
    for(let i = 0; i < n; i++)
        this.parent[i] = i;

    this.find = (x) => {
        if(this.parent[x] === x)
            return this.parent[x];

        return this.find(this.parent[x]);
    }

    this.union = (x,y) => {
        this.parent[this.find(x)] = this.find(y);
    }
}

function main(){
    let n = pi(readline());
    let mapX = new Array(1005);
    let mapY = new Array(1005);
    mapX.fill(-1);
    mapY.fill(-1);
    let uf = new dsu(n);

    for(let i = 0; i < n; i++){
        let [x,y] = ti(readline().split(' '));
        if(mapX[x] !== -1){
            uf.union(mapX[x], i);
        }else{
            mapX[x] = i;
        }

        if(mapY[y] !== -1){
            uf.union(mapY[y], i);
        }else{
            mapY[y] = i;
        }
    }

    let res = 0;
    for(let i = 0; i < n; i++)
        if(uf.parent[i] === i)
            res += 1;

    console.log(Math.floor(res / 2));
}

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Queue = require('../queue');
var Stack = require('../stack');

var Graph = function () {
    function Graph() {
        var _this = this;

        var nodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var directed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

        _classCallCheck(this, Graph);

        this.directed = directed;
        this.nodes = nodes;
        this.edges = {};
        nodes.forEach(function (node) {
            _this.edges[node] = [];
        });
    }

    _createClass(Graph, [{
        key: 'addNode',
        value: function addNode(node) {
            // is it required ?
            if (this.edges[node]) {
                throw new Error('Graph.prototype.addNode: node is already exists');
                return;
            }

            this.nodes.push(node);
            this.edges[node] = [];
        }
    }, {
        key: 'addEdge',
        value: function addEdge(node1, node2) {
            var weight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;

            this.edges[node1].push({ node: node2, weight: weight });

            if (!this.directed) {
                this.edges[node2].push({ node: node1, weight: weight });
            }
        }
    }]);

    return Graph;
}();

module.exports = Graph;

},{"../queue":3,"../stack":4}],2:[function(require,module,exports){
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = function () {
    function Node(value) {
        _classCallCheck(this, Node);

        this.value = value;
        this.nextNode = null;
        this.prevNode = null;
    }

    _createClass(Node, [{
        key: "getValue",
        value: function getValue() {
            return this.value;
        }
    }, {
        key: "setValue",
        value: function setValue(value) {
            this.value = value;
        }
    }, {
        key: "setNext",
        value: function setNext(nextNodeLink) {
            this.nextNode = nextNodeLink;
        }
    }, {
        key: "setPrev",
        value: function setPrev(prevNodeLink) {
            this.prevNode = prevNodeLink;
        }
    }, {
        key: "getNext",
        value: function getNext() {
            return this.nextNode;
        }
    }, {
        key: "getPrev",
        value: function getPrev() {
            return this.prevNode;
        }
    }]);

    return Node;
}();

module.exports = Node;

},{}],3:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Queue = function () {
    function Queue() {
        _classCallCheck(this, Queue);

        this.firstItemLink = null;
        this.lastItemLink = null;
    }

    _createClass(Queue, [{
        key: 'enqueue',
        value: function enqueue(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.lastItemLink = node;
                this.firstItemLink = node;
            } else {
                this.lastItemLink.setNext(node);
                this.lastItemLink = node;
            }

            return node;
        }
    }, {
        key: 'dequeue',
        value: function dequeue() {
            if (this.isEmpty()) {
                return undefined;
            }

            if (this.lastItemLink === this.firstItemLink) {
                this.lastItemLink = null;
            }

            var firstItem = this.firstItemLink;

            this.firstItemLink = this.firstItemLink.getNext();

            return firstItem.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.firstItemLink;
        }
    }]);

    return Queue;
}();

module.exports = Queue;

},{"../node":2}],4:[function(require,module,exports){
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Node = require('../node');

var Stack = function () {
    function Stack() {
        _classCallCheck(this, Stack);

        this.topItemLink = null;
    }

    _createClass(Stack, [{
        key: 'push',
        value: function push(item) {
            var node = new Node(item);

            if (this.isEmpty()) {
                this.topItemLink = node;
            } else {
                node.setPrev(this.topItemLink);
                this.topItemLink = node;
            }

            return node;
        }
    }, {
        key: 'pop',
        value: function pop() {
            if (this.isEmpty()) {
                return undefined;
            }

            var topItemLink = this.topItemLink;

            this.topItemLink = this.topItemLink.getPrev();

            return topItemLink.getValue();
        }
    }, {
        key: 'isEmpty',
        value: function isEmpty() {
            return !this.topItemLink;
        }
    }]);

    return Stack;
}();

module.exports = Stack;

},{"../node":2}],5:[function(require,module,exports){
'use strict';

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var Graph = require('../libs/graph');
var Queue = require('../libs/queue');

var n = parseInt(readline());
var arr = [];
for (var i = 0; i < n; i++) {
    var _readline$split$map = readline().split(' ').map(function (v) {
        return parseInt(v);
    }),
        _readline$split$map2 = _slicedToArray(_readline$split$map, 2),
        x = _readline$split$map2[0],
        y = _readline$split$map2[1];

    arr.push({ x: x, y: y, visited: false });
}

var amountOfGroups = 0;

// Бежим по всем клеткам.
for (var _i = 0; _i < n; _i++) {
    if (arr[_i].visited) {
        continue;
    }
    // Если кленка не посещена берем в работу
    // и увеличиваем количество групп на 1
    amountOfGroups++;
    for (var j = 0; j < n; j++) {
        if (arr[_i].x === arr[j].x || arr[_i].y === arr[j].y) {
            arr[j].visited = true;
        }
    }
}

write(amountOfGroups - 1);

},{"../libs/graph":1,"../libs/queue":3}]},{},[5]);


There are $$$n$$$ piles of stones, where the $$$i$$$-th pile has $$$a_i$$$ stones. Two people play a game, where they take alternating turns removing stones.In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who cannot make a move (because all piles are empty) loses the game. If both players play optimally, determine the winner of the game.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$)  — the number of piles. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 10^9$$$)  — $$$a_i$$$ is equal to the number of stones in the $$$i$$$-th pile. It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, if the player who makes the first move will win, output "First". Otherwise, output "Second".

First
Second
Second
First
First
Second
First

NoteIn the first test case, the first player will win the game. His winning strategy is:   The first player should take the stones from the first pile. He will take $$$1$$$ stone. The numbers of stones in piles will be $$$[1, 5, 4]$$$.  The second player should take the stones from the first pile. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 5, 4]$$$.  The first player should take the stones from the second pile because the first pile is empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 1, 4]$$$.  The second player should take the stones from the second pile because the first pile is empty. He will take $$$1$$$ stone because he can't take any other number of stones. The numbers of stones in piles will be $$$[0, 0, 4]$$$.  The first player should take the stones from the third pile because the first and second piles are empty. He will take $$$4$$$ stones. The numbers of stones in piles will be $$$[0, 0, 0]$$$.  The second player will lose the game because all piles will be empty.

function solve() {
   n = Number(read());
   var firstNotOne = n - 1;
   var found = false;

   readArray(function(elem, i) {
      if (elem !== '1' && !found) {
         firstNotOne = i;
         found = true;
      }
   });
   write((firstNotOne & 1) ? 'Second' : 'First');
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const t = Number(readLine())
    for (let i = 0; i < t; i++) {
        const n = Number(readLine())
        const as = readLine().split(/\s/).map(Number)
        const i = as.findIndex(a => a > 1)
        console.log(i < 0 ? as.length % 2 === 0 ? 'Second' : 'First' : i % 2 === 0 ? 'First' : 'Second')
    }
}

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

    B();
});

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

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

    return a;
}

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

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));

        let map = new Array(1000+10);

        for(let i = 0; i < a.length; i++)
            map[a[i]] = 1;

        let isFound = false;
        for(let i = 0; i < b.length; i++){
            if(map[b[i]] === 1){
                console.log('YES');
                console.log(1, b[i]);
                isFound = true;
                break;
            }
        }

        if(!isFound)
            console.log('NO');
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        let turn = 0;
        for(let i = 0; i < a.length; i++){
            if(i === n-1){
                console.log(turn === 0 ? 'First' : 'Second');
            }
            else if(a[i] === 1){
                turn = turn === 0 ? 1 : 0;
            }else{
                console.log(turn === 0 ? 'First' : 'Second');
                break;
            }
        }
    }
}

function solve() {
   n = Number(read());
   var firstNotOne = n - 1;
   var found = false;

   readArray(function(elem, i) {
      if (elem !== '1' && !found) {
         firstNotOne = i;
         found = true;
      }
   });
   write(firstNotOne + ' ' + ((firstNotOne & 1) ? 'Second' : 'First'));
}

function init() {
   var T;
   T = 1;
   T = Number(read());
   for (var t = 0; t < T; t++) {
      solve();
   }
}

function sortF(a, b) {
   if (a < b) {
      return -1;
   }
   if (a > b) {
      return 1;
   }
   return 0;
}

function readArray(f) {
   return read().split(' ').map(f);
}

var isNode = typeof console !== 'undefined';
var MEMORY = [];
var MEMORY_INDEX = 0;
if (isNode) {
   var fs = require('fs');
   var path = require('path');

   var inTextName;
   var outTextName;

   var needWriteFile = false;

   var writeResult = '';
   if (process.argv.length === 5) {
      inTextName = process.argv[3];
      outTextName = process.argv[4];
   }

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      var RL = require('readline').createInterface({
         input : process.stdin,
         output : process.stdout
      });

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

      RL.on('close', init);
   }
} else {
   init();
}

function write(value) {
   if (needWriteFile) {
      writeResult += value + '\n';
      return;
   }
   isNode ? console.log(value) : print(value);
}
function read() {
   return isNode ? MEMORY[MEMORY_INDEX++] : readline();
}

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

    B();
});

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

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

    return a;
}

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

function A(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,m] = ti(readline().split(' '));
        let a = ti(readline().split(' '));
        let b = ti(readline().split(' '));

        let map = new Array(1000+10);

        for(let i = 0; i < a.length; i++)
            map[a[i]] = 1;

        let isFound = false;
        for(let i = 0; i < b.length; i++){
            if(map[b[i]] === 1){
                console.log('YES');
                console.log(1, b[i]);
                isFound = true;
                break;
            }
        }

        if(!isFound)
            console.log('NO');
    }
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let n = pi(readline());
        let a = ti(readline().split(' '));

        let turn = 0;
        for(let i = 0; i < a.length; i++){
            if(a[i] === 1){
                if(i === n-1){
                    console.log(turn === 0 ? 'First' : 'Second');
                }
                else{
                    turn = turn === 0 ? 1 : 0;
                }
            }else{
                if(i < n-1){
                    if(i+1 === n-1){
                        turn = turn;
                    }else{
                        if(a[i+1] === 1){
                            turn = turn === 0 ? 1 : 0;
                        }
                    }
                }else{
                    console.log(turn === 0 ? 'First' : 'Second');
                }
            }
        }
    }
}