Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
//[no]param
//不明値:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
function myconv(i,no){switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}
function Main() {
    var t = myconv(next(),1);
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var N = myconv(next(),1) * 2;
        var list = myconv(next(),4);
        list.sort(function(a,b){
            return a -b;
        });
        output[i] = Math.abs(list[N / 2 - 1] - list[N / 2]);
    }
    myout(myconv(output,9));
}

'use strict'

const problem = (n, a) => {
    a.sort((x, y) => x - y)
    return a[n] - a[n-1]
}
let t = +readline();
while(t--) print(problem(+readline(), readline().split(' ').map(i => +i)))

function readNum() {
  return Number(readline());
}
function readStringArray() {
  return readline().split(" ");
}
function readNumArray() {
  return readStringArray().map(Number);
}

function main() {
  var testCasesNum = readNum();
  for (var i = 0; i < testCasesNum; i++) {
    var n = readNum();
    var arr = readNumArray();
    var sorted = arr.sort((a, b) => a - b);
    print(sorted[n] - sorted[n - 1]);
  }
}
main()

'use strict';

let currentLine = 0, inputLine = [];

const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => { inputLine.push(line); });
rl.on('close', () =>{ main(inputLine); } );

function readALine() { return inputLine[currentLine++]; }
function printALine(str) { console.log(str); }

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function stringArrayToNumbers(str) {
    return str.split(' ').map(Number);
}

function sortIntegersInArray(arr) {
    return arr.sort((a, b) => a - b);
}

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    if( result.length % 2 == 0 ) {
        result.pop();
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    if( arr.length % 2 == 1 ) {
        return arr[index];
    }
    return (arr[index] + arr[index-1])/2;
}

function doIt( n, arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    result = Math.abs(arr2[n] - arr2[n-1]);
    return result;
}

function main( inLines ) {

    inputLine = inLines;

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var n = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(n, arr);
        printALine(result);
    }

}

module.exports.main = main;

const mediana = arr => arr[Math.ceil(arr.length/2)]

const processData = (lines) => {
  const count = lines[0]

  for (i = 0; i < count; i++){
    const nums = lines[i*2 + 2].split(' ').map(x => +x)
    const sortedNums = nums.sort((a, b) => a - b)
    const [a, b] = [sortedNums[sortedNums.length/2], sortedNums[sortedNums.length/2 - 1]]
    console.log(Math.abs(a - b))
  }
}

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

'use strict';

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

const lines = [];
let nextLine = 0;
rl.on('line', (line) => {
  lines.push(line);
});

rl.on('close', () => {
  main();
});

function readline() {
  return lines[nextLine++];
}

function solve(arr) {
  const n = arr.length;
  const n2 = n / 2;
  arr.sort((a, b) => a - b);
  return arr[n2] - arr[n2-1];
}

function main() {
  const t = parseInt(readline());
  // console.log({t});
  for(let i = 0; i < t; i++) {
    readline();
    const arr = readline().split(' ').map(Number);
    const res = solve(arr);
    console.log(res);
  }
}

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

const input = [];
readline.on('line', line => input.push(line));

readline.on('close', () => {
    let n = parseInt(input[0]);
    for (let i = 1; i < 2 * n + 1; i += 2) {
        let len = parseInt(input[i]);
        let students = input[i + 1].split(' ').map(x => parseInt(x));
        students.sort((a, b) => a - b);

        console.log(students[len] - students[len - 1]);
    }
});

// Time Complexity O(n)
function processData(input) {
    input = input.trim().split('\n')
    var t = Number(input[0])
    // console.log(t)
    var line = 1
    for(var j = 0;j<t;j++){
       var n = Number(input[line++])*2
        var a = input[line++].trim().split(' ').map(a=>parseInt(a)).sort((a,b)=>(a-b))
        // console.log(n,a)
        var res = findSum(n,a)
        console.log(res)

    }
    function findSum(n,a){
      var res = Math.abs(a[n/2]-a[n/2-1])
      return res
    }
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

var inputLines = null;

function readALine() {
    if( inputLines ) { return inputLines.shift(); }
    return readline();
}

function printALine(str) {
    if( typeof print !== 'undefined' ) print(str); else console.log(str);
}

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function stringArrayToNumbers(str) {
    return str.split(' ').map(Number);
}

function sortIntegersInArray(arr) {
    return arr.sort((a, b) => a - b);
}

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    return arr[index];
}

function doIt( arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    var a1 = splitArray(0, arr2);
    var a2 = splitArray(1, arr2);
    var m1 = getMedian(a1);
    var m2 = getMedian(a2);
    result = Math.abs(m2 - m1);
    return result;
}

function main( inLines ) {

    inputLines = inLines;

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

module.exports = { main: main, inputLines: inputLines };

'use strict';

let currentLine = 0, inputLine = [];

const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => { inputLine.push(line); });
rl.on('close', () =>{ main(inputLine); } );

function readALine() { return inputLine[currentLine++]; }
function printALine(str) { console.log(str); }

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function stringArrayToNumbers(str) {
    return str.split(' ').map(Number);
}

function sortIntegersInArray(arr) {
    return arr.sort((a, b) => a - b);
}

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    if( arr.length % 2 == 1 ) {
        return arr[index];
    }
    return (arr[index] + arr[index-1])/2;
}

function doIt( arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    var a1 = splitArray(0, arr2);
    var a2 = splitArray(1, arr2);
    var m1 = getMedian(a1);
    var m2 = getMedian(a2);
    result = Math.floor(Math.abs(m2 - m1));
    return result;
}

function main( inLines ) {

    inputLine = inLines;

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

module.exports.main = main;

'use strict';

let currentLine = 0, inputLine = [];

const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => { inputLine.push(line); });
rl.on('close', () =>{ main(inputLine); } );

function readALine() { return inputLine[currentLine++]; }
function printALine(str) { console.log(str); }

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function stringArrayToNumbers(str) {
    return str.split(' ').map(Number);
}

function sortIntegersInArray(arr) {
    return arr.sort((a, b) => a - b);
}

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    return arr[index];
}

function doIt( arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    var a1 = splitArray(0, arr2);
    var a2 = splitArray(1, arr2);
    var m1 = getMedian(a1);
    var m2 = getMedian(a2);
    result = Math.abs(m2 - m1);
    return result;
}

function main( inLines ) {

    inputLine = inLines;

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

module.exports.main = main;

'use strict';

let currentLine = 0, inputLine = [];

const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
rl.on('line', line => { inputLine.push(line); });
rl.on('close', () =>{ main(inputLine); } );

function readALine() { return inputLine[currentLine++]; }
function printALine(str) { console.log(str); }

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function stringArrayToNumbers(str) {
    return str.split(' ').map(Number);
}

function sortIntegersInArray(arr) {
    return arr.sort((a, b) => a - b);
}

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    if( result.length % 2 == 0 ) {
        result.pop();
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    if( arr.length % 2 == 1 ) {
        return arr[index];
    }
    return (arr[index] + arr[index-1])/2;
}

function doIt( arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    var a1 = splitArray(0, arr2);
    var a2 = splitArray(1, arr2);
    var m1 = getMedian(a1);
    var m2 = getMedian(a2);
    result = Math.floor(Math.abs(m2 - m1));
    return result;
}

function main( inLines ) {

    inputLine = inLines;

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

module.exports.main = main;

var inputLines = null;

function readALine() {
    if( inputLines ) { return inputLines.shift(); }
    return readline();
}

function printALine(str) {
    console.log(str);
}

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function stringArrayToNumbers(str) {
    return str.split(' ').map(Number);
}

function sortIntegersInArray(arr) {
    return arr.sort((a, b) => a - b);
}

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    return arr[index];
}

function doIt( arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    var a1 = splitArray(0, arr2);
    var a2 = splitArray(1, arr2);
    var m1 = getMedian(a1);
    var m2 = getMedian(a2);
    result = Math.abs(m2 - m1);
    return result;
}

function main( inLines ) {

    inputLines = inLines;

    console.log("A");

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

module.exports = { main: main, inputLines: inputLines };

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function printALine(str) {
    console.log(str);
}

function stringArrayToNumbers(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( parseInt(array[i]) );
    }
    return result;
}

function stringArrayToBigInts(str) {
    var array = str.split(" ");
    var result = [];
    for( var i = 0; i < array.length; i++ ) {
        result.push( BigInt(array[i]) );
    }
    return result;
}

function sumOfAllElementsInArray(arr) {
    var result = 0;
    for( var i = 0; i < arr.length; i++ ) {
        result += arr[i];
    }
    return result;
}

function productOfAllElementsInArray(arr) {
    var result = 1;
    for( var i = 0; i < arr.length; i++ ) {
        result *= arr[i];
    }
    return result;
}

function maxOfElementsInArray(arr) {
    var result = 0;
    for( var i = 0; i < arr.length; i++ ) {
        if( arr[i] > result ) {
            result = arr[i];
        }
    }
    return result;
}

function sortIntegersInArray(arr) {
    function sortNumber(a, b) {
       return a - b;
    }
    arr.sort(sortNumber);
    return arr;
}

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    return arr[index];
}

function doIt( arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    //console.log("Array2 = " + arr2);
    var a1 = splitArray(0, arr2);
    //console.log("  a1 = " + a1);
    var a2 = splitArray(1, arr2);
    //console.log("  a2 = " + a2);
    var m1 = getMedian(a1);
    var m2 = getMedian(a2);
    result = Math.abs(m2 - m1);
    return result;
}

function main() {

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

var inputLines = null;

function readALine() {
    if( inputLines ) { return inputLines.shift(); }
    return readline();
}

function printALine(str) {
    console.log(str);
}

// ======================================================
// B. Assigning to Classes
// http://codeforces.com/contest/1300/problem/B
// ======================================================

function stringArrayToNumbers(str) {
    return str.split(' ').map(Number);
}

function sortIntegersInArray(arr) {
    return arr.sort((a, b) => a - b);
}

function splitArray(startIndex, arr) {
    var result = [];
    for( var i = startIndex; i < arr.length; i+=2 ) {
        result.push(arr[i]);
    }
    return result;
}

function getMedian(arr) {
    var index = Math.floor(arr.length/2);
    return arr[index];
}

function doIt( arr ) {
    var result = 0;
    var arr2 = sortIntegersInArray(arr);
    var a1 = splitArray(0, arr2);
    var a2 = splitArray(1, arr2);
    var m1 = getMedian(a1);
    var m2 = getMedian(a2);
    result = Math.abs(m2 - m1);
    return result;
}

function main( inLines ) {

    inputLines = inLines;

    var numOfTests = parseInt(readALine());
    for( var i = 0; i < numOfTests; i++ ) {
        var string1 = readALine();
        var numOfElements = parseInt(string1);
        var string2 = readALine();
        var arr = stringArrayToNumbers(string2);
        var result = doIt(arr);
        printALine(result);
    }

}

module.exports = { main: main, inputLines: inputLines };


function myout(t){print(t);}//standard output
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}
function Main() {
  var tmp = myconv(readline(),4);
  var n = tmp[0];
  var ink = tmp[1];
  var list = [];
  var reqlist = [];
  var inputSet = new Set();
  for(var i = 0; i < n; i++){
      var strin = readline();
      list.push(myconv(strin,6));
      inputSet.add(strin);
  }
  var output = 0;
  for(var i = 0; i < n-1; i++){
      for(var j = i+1; j < n; j++){
          var reqstr = "";
          for(var k = 0; k < ink; k++){
              if(list[i][k] == list[j][k]){
                  reqstr += list[i][k];
              }else{
                  if((list[i][k] == "E" && list[j][k] == "T") ||
                    (list[i][k] == "T" && list[j][k] == "E")){
                      reqstr += "S";
                  }else if((list[i][k] == "S" && list[j][k] == "T") ||
                    (list[i][k] == "T" && list[j][k] == "S")){
                      reqstr += "E";
                  }else{
                      reqstr += "T";
                  }
              }
          }
          if(inputSet.has(reqstr)){
            output++;
          }
      }
  }
  myout(output / 3);
}

Main();

'use strict';

var readline = require('readline');

function nkStdinReader() {
  return new Promise(function (resolve) {
    var stdin = readline.createInterface(process.stdin);
    var output = [];
    var lines;
    stdin.on('line', function (line) {
      output.push(line);

      if (output.length === 1) {
        lines = +line.split(' ')[0];
      } else if (--lines === 0) {
        stdin.close();
        resolve(output);
      }
    });
  });
}

// https://codeforces.com/problemset/problem/1287/B
var setCreator = new Map([['EE', 'E'], ['ES', 'T'], ['ET', 'S'], ['SE', 'T'], ['SS', 'S'], ['ST', 'E'], ['TE', 'S'], ['TS', 'E'], ['TT', 'T']]);

function getSetCard(card1, card2) {
  var card = '';

  for (var x = 0; x < card1.length; x++) {
    card += setCreator.get(card1[x] + card2[x]);
  }

  return card;
}

nkStdinReader().then(function (input) {
  var cards = input.slice(1);
  var cardLookup = new Map(cards.map(function (c, i) {
    return [c, i];
  }));
  var output = 0;

  for (var x = 0; x < cards.length - 2; x++) {
    for (var y = x + 1; y < cards.length - 1; y++) {
      var setCard = getSetCard(cards[x], cards[y]);

      if ((cardLookup.get(setCard) || 0) > y) {
        output++;
      }
    }
  }

  console.log(output);
});

'use strict';

var readline = require('readline');

function nkStdinReader() {
  return new Promise(function (resolve) {
    var stdin = readline.createInterface(process.stdin);
    var output = [];
    var lines;
    stdin.on('line', function (line) {
      output.push(line);

      if (output.length === 1) {
        lines = +line.split(' ')[0];
      } else if (--lines === 0) {
        stdin.close();
        resolve(output);
      }
    });
  });
}

// https://codeforces.com/problemset/problem/1287/B

function getSetCard(card1, card2) {
  var card = '';

  var _loop = function _loop(x) {
    var a = card1[x];
    var b = card2[x];

    if (a === b) {
      card += a;
    } else {
      card += ['E', 'S', 'T'].find(function (c) {
        return c !== a && c !== b;
      });
    }
  };

  for (var x = 0; x < card1.length; x++) {
    _loop(x);
  }

  return card;
}

nkStdinReader().then(function (input) {
  var cards = input.slice(1);
  var cardLookup = new Map(cards.map(function (c, i) {
    return [c, i];
  }));
  var output = 0;

  for (var x = 0; x < cards.length - 2; x++) {
    for (var y = x + 1; y < cards.length - 1; y++) {
      var setCard = getSetCard(cards[x], cards[y]);

      if (cardLookup.get(setCard) || 0 > y) {
        output++;
      }
    }
  }

  console.log(output);
});

'use strict';

var readline = require('readline');

/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0

THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.

See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isFunction(x) {
    return typeof x === 'function';
}
//# sourceMappingURL=isFunction.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var _enable_super_gross_mode_that_will_cause_bad_things = false;
var config = {
    Promise: undefined,
    set useDeprecatedSynchronousErrorHandling(value) {
        if (value) {
            var error = /*@__PURE__*/ new Error();
            /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
        }
        _enable_super_gross_mode_that_will_cause_bad_things = value;
    },
    get useDeprecatedSynchronousErrorHandling() {
        return _enable_super_gross_mode_that_will_cause_bad_things;
    },
};
//# sourceMappingURL=config.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function hostReportError(err) {
    setTimeout(function () { throw err; }, 0);
}
//# sourceMappingURL=hostReportError.js.map

/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */
var empty = {
    closed: true,
    next: function (value) { },
    error: function (err) {
        if (config.useDeprecatedSynchronousErrorHandling) {
            throw err;
        }
        else {
            hostReportError(err);
        }
    },
    complete: function () { }
};
//# sourceMappingURL=Observer.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();
//# sourceMappingURL=isArray.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isObject(x) {
    return x !== null && typeof x === 'object';
}
//# sourceMappingURL=isObject.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {
    function UnsubscriptionErrorImpl(errors) {
        Error.call(this);
        this.message = errors ?
            errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
        this.name = 'UnsubscriptionError';
        this.errors = errors;
        return this;
    }
    UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return UnsubscriptionErrorImpl;
})();
var UnsubscriptionError = UnsubscriptionErrorImpl;
//# sourceMappingURL=UnsubscriptionError.js.map

/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */
var Subscription = /*@__PURE__*/ (function () {
    function Subscription(unsubscribe) {
        this.closed = false;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (unsubscribe) {
            this._unsubscribe = unsubscribe;
        }
    }
    Subscription.prototype.unsubscribe = function () {
        var errors;
        if (this.closed) {
            return;
        }
        var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
        this.closed = true;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (_parentOrParents instanceof Subscription) {
            _parentOrParents.remove(this);
        }
        else if (_parentOrParents !== null) {
            for (var index = 0; index < _parentOrParents.length; ++index) {
                var parent_1 = _parentOrParents[index];
                parent_1.remove(this);
            }
        }
        if (isFunction(_unsubscribe)) {
            try {
                _unsubscribe.call(this);
            }
            catch (e) {
                errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];
            }
        }
        if (isArray(_subscriptions)) {
            var index = -1;
            var len = _subscriptions.length;
            while (++index < len) {
                var sub = _subscriptions[index];
                if (isObject(sub)) {
                    try {
                        sub.unsubscribe();
                    }
                    catch (e) {
                        errors = errors || [];
                        if (e instanceof UnsubscriptionError) {
                            errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
                        }
                        else {
                            errors.push(e);
                        }
                    }
                }
            }
        }
        if (errors) {
            throw new UnsubscriptionError(errors);
        }
    };
    Subscription.prototype.add = function (teardown) {
        var subscription = teardown;
        if (!teardown) {
            return Subscription.EMPTY;
        }
        switch (typeof teardown) {
            case 'function':
                subscription = new Subscription(teardown);
            case 'object':
                if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
                    return subscription;
                }
                else if (this.closed) {
                    subscription.unsubscribe();
                    return subscription;
                }
                else if (!(subscription instanceof Subscription)) {
                    var tmp = subscription;
                    subscription = new Subscription();
                    subscription._subscriptions = [tmp];
                }
                break;
            default: {
                throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
            }
        }
        var _parentOrParents = subscription._parentOrParents;
        if (_parentOrParents === null) {
            subscription._parentOrParents = this;
        }
        else if (_parentOrParents instanceof Subscription) {
            if (_parentOrParents === this) {
                return subscription;
            }
            subscription._parentOrParents = [_parentOrParents, this];
        }
        else if (_parentOrParents.indexOf(this) === -1) {
            _parentOrParents.push(this);
        }
        else {
            return subscription;
        }
        var subscriptions = this._subscriptions;
        if (subscriptions === null) {
            this._subscriptions = [subscription];
        }
        else {
            subscriptions.push(subscription);
        }
        return subscription;
    };
    Subscription.prototype.remove = function (subscription) {
        var subscriptions = this._subscriptions;
        if (subscriptions) {
            var subscriptionIndex = subscriptions.indexOf(subscription);
            if (subscriptionIndex !== -1) {
                subscriptions.splice(subscriptionIndex, 1);
            }
        }
    };
    Subscription.EMPTY = (function (empty) {
        empty.closed = true;
        return empty;
    }(new Subscription()));
    return Subscription;
}());
function flattenUnsubscriptionErrors(errors) {
    return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);
}
//# sourceMappingURL=Subscription.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var rxSubscriber = /*@__PURE__*/ (function () {
    return typeof Symbol === 'function'
        ? /*@__PURE__*/ Symbol('rxSubscriber')
        : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();
})();
//# sourceMappingURL=rxSubscriber.js.map

/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */
var Subscriber = /*@__PURE__*/ (function (_super) {
    __extends(Subscriber, _super);
    function Subscriber(destinationOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this.syncErrorValue = null;
        _this.syncErrorThrown = false;
        _this.syncErrorThrowable = false;
        _this.isStopped = false;
        switch (arguments.length) {
            case 0:
                _this.destination = empty;
                break;
            case 1:
                if (!destinationOrNext) {
                    _this.destination = empty;
                    break;
                }
                if (typeof destinationOrNext === 'object') {
                    if (destinationOrNext instanceof Subscriber) {
                        _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
                        _this.destination = destinationOrNext;
                        destinationOrNext.add(_this);
                    }
                    else {
                        _this.syncErrorThrowable = true;
                        _this.destination = new SafeSubscriber(_this, destinationOrNext);
                    }
                    break;
                }
            default:
                _this.syncErrorThrowable = true;
                _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
                break;
        }
        return _this;
    }
    Subscriber.prototype[rxSubscriber] = function () { return this; };
    Subscriber.create = function (next, error, complete) {
        var subscriber = new Subscriber(next, error, complete);
        subscriber.syncErrorThrowable = false;
        return subscriber;
    };
    Subscriber.prototype.next = function (value) {
        if (!this.isStopped) {
            this._next(value);
        }
    };
    Subscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            this.isStopped = true;
            this._error(err);
        }
    };
    Subscriber.prototype.complete = function () {
        if (!this.isStopped) {
            this.isStopped = true;
            this._complete();
        }
    };
    Subscriber.prototype.unsubscribe = function () {
        if (this.closed) {
            return;
        }
        this.isStopped = true;
        _super.prototype.unsubscribe.call(this);
    };
    Subscriber.prototype._next = function (value) {
        this.destination.next(value);
    };
    Subscriber.prototype._error = function (err) {
        this.destination.error(err);
        this.unsubscribe();
    };
    Subscriber.prototype._complete = function () {
        this.destination.complete();
        this.unsubscribe();
    };
    Subscriber.prototype._unsubscribeAndRecycle = function () {
        var _parentOrParents = this._parentOrParents;
        this._parentOrParents = null;
        this.unsubscribe();
        this.closed = false;
        this.isStopped = false;
        this._parentOrParents = _parentOrParents;
        return this;
    };
    return Subscriber;
}(Subscription));
var SafeSubscriber = /*@__PURE__*/ (function (_super) {
    __extends(SafeSubscriber, _super);
    function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this._parentSubscriber = _parentSubscriber;
        var next;
        var context = _this;
        if (isFunction(observerOrNext)) {
            next = observerOrNext;
        }
        else if (observerOrNext) {
            next = observerOrNext.next;
            error = observerOrNext.error;
            complete = observerOrNext.complete;
            if (observerOrNext !== empty) {
                context = Object.create(observerOrNext);
                if (isFunction(context.unsubscribe)) {
                    _this.add(context.unsubscribe.bind(context));
                }
                context.unsubscribe = _this.unsubscribe.bind(_this);
            }
        }
        _this._context = context;
        _this._next = next;
        _this._error = error;
        _this._complete = complete;
        return _this;
    }
    SafeSubscriber.prototype.next = function (value) {
        if (!this.isStopped && this._next) {
            var _parentSubscriber = this._parentSubscriber;
            if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                this.__tryOrUnsub(this._next, value);
            }
            else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;
            if (this._error) {
                if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(this._error, err);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, this._error, err);
                    this.unsubscribe();
                }
            }
            else if (!_parentSubscriber.syncErrorThrowable) {
                this.unsubscribe();
                if (useDeprecatedSynchronousErrorHandling) {
                    throw err;
                }
                hostReportError(err);
            }
            else {
                if (useDeprecatedSynchronousErrorHandling) {
                    _parentSubscriber.syncErrorValue = err;
                    _parentSubscriber.syncErrorThrown = true;
                }
                else {
                    hostReportError(err);
                }
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.complete = function () {
        var _this = this;
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            if (this._complete) {
                var wrappedComplete = function () { return _this._complete.call(_this._context); };
                if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(wrappedComplete);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, wrappedComplete);
                    this.unsubscribe();
                }
            }
            else {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            this.unsubscribe();
            if (config.useDeprecatedSynchronousErrorHandling) {
                throw err;
            }
            else {
                hostReportError(err);
            }
        }
    };
    SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
        if (!config.useDeprecatedSynchronousErrorHandling) {
            throw new Error('bad call');
        }
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                parent.syncErrorValue = err;
                parent.syncErrorThrown = true;
                return true;
            }
            else {
                hostReportError(err);
                return true;
            }
        }
        return false;
    };
    SafeSubscriber.prototype._unsubscribe = function () {
        var _parentSubscriber = this._parentSubscriber;
        this._context = null;
        this._parentSubscriber = null;
        _parentSubscriber.unsubscribe();
    };
    return SafeSubscriber;
}(Subscriber));
//# sourceMappingURL=Subscriber.js.map

/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */
function canReportError(observer) {
    while (observer) {
        var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
        if (closed_1 || isStopped) {
            return false;
        }
        else if (destination && destination instanceof Subscriber) {
            observer = destination;
        }
        else {
            observer = null;
        }
    }
    return true;
}
//# sourceMappingURL=canReportError.js.map

/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */
function toSubscriber(nextOrObserver, error, complete) {
    if (nextOrObserver) {
        if (nextOrObserver instanceof Subscriber) {
            return nextOrObserver;
        }
        if (nextOrObserver[rxSubscriber]) {
            return nextOrObserver[rxSubscriber]();
        }
    }
    if (!nextOrObserver && !error && !complete) {
        return new Subscriber(empty);
    }
    return new Subscriber(nextOrObserver, error, complete);
}
//# sourceMappingURL=toSubscriber.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();
//# sourceMappingURL=observable.js.map

/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function noop() { }
//# sourceMappingURL=noop.js.map

/** PURE_IMPORTS_START _noop PURE_IMPORTS_END */
function pipeFromArray(fns) {
    if (!fns) {
        return noop;
    }
    if (fns.length === 1) {
        return fns[0];
    }
    return function piped(input) {
        return fns.reduce(function (prev, fn) { return fn(prev); }, input);
    };
}
//# sourceMappingURL=pipe.js.map

/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */
var Observable = /*@__PURE__*/ (function () {
    function Observable(subscribe) {
        this._isScalar = false;
        if (subscribe) {
            this._subscribe = subscribe;
        }
    }
    Observable.prototype.lift = function (operator) {
        var observable = new Observable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    };
    Observable.prototype.subscribe = function (observerOrNext, error, complete) {
        var operator = this.operator;
        var sink = toSubscriber(observerOrNext, error, complete);
        if (operator) {
            sink.add(operator.call(sink, this.source));
        }
        else {
            sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
                this._subscribe(sink) :
                this._trySubscribe(sink));
        }
        if (config.useDeprecatedSynchronousErrorHandling) {
            if (sink.syncErrorThrowable) {
                sink.syncErrorThrowable = false;
                if (sink.syncErrorThrown) {
                    throw sink.syncErrorValue;
                }
            }
        }
        return sink;
    };
    Observable.prototype._trySubscribe = function (sink) {
        try {
            return this._subscribe(sink);
        }
        catch (err) {
            if (config.useDeprecatedSynchronousErrorHandling) {
                sink.syncErrorThrown = true;
                sink.syncErrorValue = err;
            }
            if (canReportError(sink)) {
                sink.error(err);
            }
            else {
                console.warn(err);
            }
        }
    };
    Observable.prototype.forEach = function (next, promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var subscription;
            subscription = _this.subscribe(function (value) {
                try {
                    next(value);
                }
                catch (err) {
                    reject(err);
                    if (subscription) {
                        subscription.unsubscribe();
                    }
                }
            }, reject, resolve);
        });
    };
    Observable.prototype._subscribe = function (subscriber) {
        var source = this.source;
        return source && source.subscribe(subscriber);
    };
    Observable.prototype[observable] = function () {
        return this;
    };
    Observable.prototype.pipe = function () {
        var operations = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            operations[_i] = arguments[_i];
        }
        if (operations.length === 0) {
            return this;
        }
        return pipeFromArray(operations)(this);
    };
    Observable.prototype.toPromise = function (promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var value;
            _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
        });
    };
    Observable.create = function (subscribe) {
        return new Observable(subscribe);
    };
    return Observable;
}());
function getPromiseCtor(promiseCtor) {
    if (!promiseCtor) {
        promiseCtor =  Promise;
    }
    if (!promiseCtor) {
        throw new Error('no Promise impl found');
    }
    return promiseCtor;
}
//# sourceMappingURL=Observable.js.map

function tnLineStdinReader() {
  return new Observable(subscribe => {
    const stdin = readline.createInterface(process.stdin);
    let tests = null;
    let n = null;
    stdin.on('line', line => {
      if (tests === null) {
        tests = +line;
      } else if (n === null) {
        n = +line;
        tests--;
      } else {
        n = null;
        subscribe.next(line);

        if (tests === 0) {
          stdin.close();
          subscribe.complete();
        }
      }
    });
  });
}

function isHappy(arr) {
  if (arr[0] <= 0 || arr[arr.length - 1] <= 0) {
    return 'NO';
  }

  let sum = 0;

  for (let x = 0; x < arr.length - 1; x++) {
    sum += arr[x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  sum = 0;

  for (let x = arr.length - 1; x > 0; x--) {
    sum += arr[x];

    if (sum <= 0) {
      return 'NO';
    }
  }

  return 'YES';
}

tnLineStdinReader().subscribe(input => {
  const arr = input.split(' ').map(i => +i);
  console.log(isHappy(arr));
});


function solve(){
    var n;

var arr=[];

n = +readline();
for(var i=0;i<n;i++){
    arr[i]=readline().split(' ');
}

//print(arr[1][2]);
var x,y,j;
for(i=0;i<n;i++){
    for(j=0;j<n;j++){
        if(+arr[i][j]===0){
            x=i;
            y=j;
        }
    }
}

//print(''+x+' '+y);
var sum=0;
if(n==1){
    print(1);
    return;
}
if(x!==0){
    for(i = 0;i<n;i++){
        sum+= +arr[0][i];
    }
}else{
    for(i = 0;i<n;i++){
        sum+= +arr[1][i];
    }
}
//print(sum);
var cur=0;
for(i = 0;i<n;++i){
    cur+=+arr[x][i];
}
arr[x][y] = (sum-cur);
//print(arr[x][y]);
if(arr[x][y]<=0){
    print(-1);
    return;
}
cur=0;//diag
for(i=0;i<n;++i){
    cur+=+arr[i][i];
}
if(cur!=sum){
    print(-1);
    return;
}
cur=0;//2diag
for(i=0;i<n;++i){
    cur+=+arr[i][n-i-1];
}
if(cur!=sum){
    print(-1);
    return;
}
var cur1=0,cur2=0;
for(i=0;i<n;++i){
    cur1=0;
    cur2=0;
    for(j=0;j<n;++j){
        cur1+=+arr[i][j];
        cur2+=+arr[j][i];
    }
    if(cur1!==sum){
        print(-1);
        return;
    }
    if(cur2!==sum){
        print(-1);
        return;
    }
}

print(arr[x][y]);

}

solve();

var n = parseInt(readline());
var i0; var j0;
var matrix = [];

var supposedsum = 0;

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

    var j = 0;
    var row = readline().split(' ').map(function(x){
        var num = parseInt(x);

        if(num === 0) {
            i0 = i;
            j0 = j;
        }

        j++;
        return num;
    });

    matrix.push(row);
}

if(n === 1) {
    print(1);
} else {

    var sumrow0 = matrix[i0].reduce(function(prev, curr){
        return prev + curr;
    });

    // take any row for calculating guessed empty grid value
    var checkrow = i0 + 1;
    if(i0 === n - 1) { // check if empty grid on bottom edge
        checkrow = i0 - 1;
    }

    supposedsum = matrix[checkrow].reduce(function(prev, curr){
        return prev + curr;
    });

    //console.log("supposedsum: " + supposedsum);

    matrix[i0][j0] = supposedsum - sumrow0;

    //console.log("matrix[i0][j0]: " + matrix[i0][j0]);

    // start checking

    if(matrix[i0][j0] > 0)
    {
        var is_solution_exist = true;

        // check every row & column
        var sum_main_diagonal = 0;
        var sum_secondary_diagonal = 0;
        for(var i = 0; i < n; i++) {

            var sumrow = 0;
            var sumcol = 0;

            for(var j = 0; j < n; j++) {

                sumrow += matrix[i][j];
                sumcol += matrix[j][i];
            }

            sum_main_diagonal += matrix[i][i];
            sum_secondary_diagonal += matrix[i][n - i - 1];

            if(sumrow !== supposedsum || sumcol !== supposedsum) {
                is_solution_exist = false;
                break;
            }
        }

        if(is_solution_exist) {
            //console.log("check sum of every diagonal");
            //console.log("sum_main_diagonal: " + sum_main_diagonal);
            //console.log("sum_secondary_diagonal: " + sum_secondary_diagonal);
            // check if every diagonal
            is_solution_exist = sum_main_diagonal == supposedsum && sum_secondary_diagonal == supposedsum;
        }

        if(is_solution_exist)
            print(matrix[i0][j0]);
        else
            print(-1);
    }
    else
        print(-1);

}

/*
    The idea to solve this problem is basically straightforward:

    Assume matrix is magic square.

    Take any sum row / column, compare it with sum row / column containing zero, the result will be guessed empty grid value,
    after that test if new value is correct (must be positive integer and by checking sum of every row, every column, main diagonal, and secondary diagonal).

    If all tests passed then the matrix is magic square, otherwise it is not.
*/

var n = parseInt(readline());
var i0; var j0;
var matrix = [];

var supposedsum = 0;

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

    var j = 0;
    var row = readline().split(' ').map(function(x){
        var num = parseInt(x);

        if(num === 0) { // try to locate position of zero value
            i0 = i;
            j0 = j;
        }

        j++;
        return num;
    });

    matrix.push(row); // construct matrix
}

if(n === 1) {
    print(1); //  basically we can print any positive integer
} else {

    // get sum of row containing zero --> we can take sum row or sum col, btw
    var sumrow0 = matrix[i0].reduce(function(prev, curr){
        return prev + curr;
    });

    // take any row for calculating guessed empty grid value
    var checkrow = i0 + 1;
    if(i0 === n - 1) { // check if empty grid on bottom edge
        checkrow = i0 - 1;
    }

    // calculate supposed sum
    supposedsum = matrix[checkrow].reduce(function(prev, curr){
        return prev + curr;
    });

    // calculate guessed value
    matrix[i0][j0] = supposedsum - sumrow0;

    // start checking
    if(matrix[i0][j0] > 0) // check if guessed value is positive integer
    {
        var is_solution_exist = true;
        var sum_main_diagonal = 0;
        var sum_secondary_diagonal = 0;

        // check every row & column
        for(var i = 0; i < n; i++) {

            var sumrow = 0;
            var sumcol = 0;

            for(var j = 0; j < n; j++) {

                sumrow += matrix[i][j];
                sumcol += matrix[j][i];
            }

            sum_main_diagonal += matrix[i][i];
            sum_secondary_diagonal += matrix[i][n - i - 1];

            if(sumrow !== supposedsum || sumcol !== supposedsum) {
                is_solution_exist = false;
                break;
            }
        }

        if(is_solution_exist) {
            // check every diagonal value compared to supposedsum
            is_solution_exist = sum_main_diagonal == supposedsum && sum_secondary_diagonal == supposedsum;
        }

        if(is_solution_exist)
            print(matrix[i0][j0]);
        else
            print(-1);
    }
    else
        print(-1);

}

var n = parseInt(readline());
var i0; var j0;
var matrix = [];

var supposedsum = 0;

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

    var j = 0;
    var row = readline().split(' ').map(function(x){
        var num = parseInt(x);

        if(num === 0) {
            i0 = i;
            j0 = j;
        }

        j++;
        return num;
    });

    matrix.push(row);
}

if(n === 1) {
    print(1);
} else {

    var sumrow0 = matrix[i0].reduce(function(prev, curr){
        return prev + curr;
    });

    // take any row for calculating guessed empty grid value
    var checkrow = i0 + 1;
    if(i0 === n - 1) { // check if empty grid on bottom edge
        checkrow = i0 - 1;
    }

    supposedsum = matrix[checkrow].reduce(function(prev, curr){
        return prev + curr;
    });

    //console.log("supposedsum: " + supposedsum);

    matrix[i0][j0] = supposedsum - sumrow0;

    //console.log("matrix[i0][j0]: " + matrix[i0][j0]);

    // start checking
    var is_solution_exist = true;

    // check every row & column
    var sum_main_diagonal = 0;
    var sum_secondary_diagonal = 0;
    for(var i = 0; i < n; i++) {

        var sumrow = 0;
        var sumcol = 0;

        for(var j = 0; j < n; j++) {

            sumrow += matrix[i][j];
            sumcol += matrix[j][i];
        }

        sum_main_diagonal += matrix[i][i];
        sum_secondary_diagonal += matrix[i][n - i - 1];

        if(sumrow !== supposedsum || sumcol !== supposedsum) {
            is_solution_exist = false;
            break;
        }
    }

    if(is_solution_exist) {
        //console.log("check sum of every diagonal");
        //console.log("sum_main_diagonal: " + sum_main_diagonal);
        //console.log("sum_secondary_diagonal: " + sum_secondary_diagonal);
        // check if every diagonal
        is_solution_exist = sum_main_diagonal == supposedsum && sum_secondary_diagonal == supposedsum;
    }

    if(is_solution_exist)
        print(matrix[i0][j0]);
    else
        print(-1);

}


process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here
let input = "";
process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
	const numbers = input.split("\n").filter(x => x.trim() !== "").filter((_, i) => i !== 0).map(Number);
	let oddCount = (numbers.map(x => x % 2 !== 0).reduce((acc, cur) => acc + cur, 0)) / 2;
	for (let i = 0; i < numbers.length; i++) {
		if (numbers[i] % 2 === 0) {
			numbers[i] /= 2;
			continue;
        }
		if (numbers[i] % 2 !== 0) {
			if (oddCount > 0) {
                numbers[i]--;
                oddCount--;
            } else {
				numbers[i]++;
			}
			numbers[i] /= 2;
		}
	}
	console.log(numbers.join("\n"));
});

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n')
  const n = parseInt(arr.shift())

  let nF = false, pF = false
  for(let i = 0; i < n; i++) {
    let num = parseInt(arr[i])
    if(num % 2 == 0) console.log(num / 2)
    else if(num == 0) {
      console.log(0)
    }

    else if(num > 0) {
      if(pF) {
        console.log((num + 1) / 2)
      }
      else {
        console.log((num - 1) / 2)
      }
      pF = !pF
    }

    else {
      if(pF) {
        console.log((num + 1) / 2)
      }
      else {
        console.log((num - 1) / 2)
      }
      pF = !pF
    }
  }
})

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

let countStr = 0;
const dataArr = [];

rl.on('line', (line) => {
  line = Number(line);
  if (!countStr) {
    countStr = line;
    return;
  }

  dataArr.push(line);
  if (dataArr.length === countStr) {
    start();
  }
});

function start() {
  let flag = true;
  for (let i of dataArr) {
    if (i % 2 === 0) {
      console.log(i / 2);
      continue;
    }

    let a;

    if (flag) {
      a = Math.floor(i / 2);
    } else {
      a = Math.ceil(i / 2);
    }

    if (a > -1 && a < 1) {
      a = 0;
    }
    console.log(a);

    flag = !flag;
  }

  rl.close();
}

var count = parseInt(readline());
// var arr = [10, -5, -5]
// var count = 3;
var balance = 0;

for (var i = 0; i < count; i++) {
  var curr = parseInt(readline());
  // var curr = arr[i]
  if (curr % 2 === 0) {
    write((curr / 2) + '\n');
  }
  else if (balance) {
    balance = 0;
    write(Math.floor(curr / 2) + '\n');
  } else {
    write(Math.ceil(curr / 2) + '\n');
    balance = 1;
  }
}

  var n = readline();

    var raing =[];
    var hadCorrection =[];
    var newRating =[];
    var sum = 0;

    for(var i=0;i<n;i++)
    {
        raing[i] = readline();
        if(raing[i]%2==0) newRating[i]=raing[i]/2;
        else
        {
            newRating[i] =Math.floor(raing[i]/2);
            hadCorrection[i]=1;
        }

        sum+=newRating[i];

    }

    for(var i=n-1;i>=0;i--)
    {
        var temp = newRating[i];
        if((sum>0 && hadCorrection[i]<0)
        || sum<0 && hadCorrection[i]>0)
        {
            newRating[i] = newRating[i]+hadCorrection[i];
            sum += newRating[i]-temp;
           // print("new rating = "+newRating[i]+" Sum : "+sum);
        }

    }

    for(var i=0;i<n;i++)print(newRating[i]);

//var input = readline()
var T = parseInt(readline());

var f1 = false;
for(var i=0; i<T; i++) {

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

        if(ar % 2 === 0) {
                print(ar / 2);

        } else if(f1) {
                print(Math.floor(ar / 2));
                f1 = false;

        } else {
                print(Math.ceil(ar / 2));
                f1 = true;
        }
}

//

process.stdin.resume();
process.stdin.setEncoding('utf8');

// your code goes here
let input = "";
process.stdin.on("data", data => input += data);
process.stdin.on("end", () => {
	console.log(input.split('\n').filter((_, i) => i !== 0).map(Number).map(x => x / 2).map(Math.round).join("\n"));
});

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

var arr = ''
process.stdin.on('data', (i) => {
  arr += i
})

process.stdin.on('end', () => {
  arr = arr.split('\n')
  const n = parseInt(arr.shift())

  let nF = false, pF = false
  for(let i = 0; i < n; i++) {
    let num = parseInt(arr[i])
    if(num % 2 == 0) console.log(num / 2)
    else if(num == 0) {
      console.log(0)
    }

    else if(num > 0) {
      if(pF) {
        console.log(Math.floor(num / 2))
      }
      else {
        console.log(Math.ceil(num / 2))
      }
      pF = !pF
    }

    else {
      if(pF) {
        console.log(Math.floor(num / 2))
      }
      else {
        console.log(Math.ceil(num / 2))
      }
      pF = !pF
    }
  }
})

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

let countStr = 0;
const dataArr = [];

rl.on('line', (line) => {
  line = Number(line);
  if (!countStr) {
    countStr = line;
    return;
  }

  dataArr.push(line);
  if (dataArr.length === countStr) {
    start();
  }
});

function start() {
  let flag = true;
  for (let i of dataArr) {
    if (i % 2 === 0) {
      console.log(i / 2);
      continue;
    }

    if (flag) {
      console.log(Math.floor(i / 2));
    } else {
      console.log(Math.ceil(i / 2));
    }

    flag = !flag;
  }

  rl.close();
}

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

let countStr = 0;
const dataArr = [];

rl.on('line', (line) => {
  line = Number(line);
  if (!countStr) {
    countStr = line;
    return;
  }

  dataArr.push(line);
  if (dataArr.length === countStr) {
    start();
  }
});

function start() {
  let flag = false;
  for (let i of dataArr) {
    if (i % 2 === 0) {
      console.log(i / 2);
      continue;
    }

    if (flag) {
      console.log(Math.floor(i / 2));
    } else {
      console.log(Math.ceil(i / 2));
    }

    flag = !flag;
  }

  rl.close();
}


'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [l, r, x] = rns(),
        [a, b] = rns();
  if (a === b) return 0;
  if (Math.abs(a - b) >= x) return 1;
  if (a - l < x && r - a < x) return -1;
  if (b - l < x && r - b < x) return -1;
  if (a - l >= x) {
    if (b - l >= x) return 2;
  }
  if (r - a >= x) {
    if (r - b >= x) return 2;
  }
  return 3;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();

'use strict';

function solve([l, r, x], [a, b]) {
    if (a === b) {
        return 0
    }

    if (Math.abs(l - r) < x) {
        return -1;
    }

    if (Math.abs(a - b) >= x) {
        return 1;
    }

    if (a > b) {
        var tmp = a;
        a = b;
        b = tmp;
    }

    if (r - b >= x || a - l >= x) {
        return 2;
    }

    if (r - a >= x && b - l >= x) {
        return 3;
    }

    return -1;
}

function main() {
    const numOfCases = rlsn();

    for (let testCase = 0; testCase < numOfCases; testCase++) {
        const l1 = rlarrn();
        const l2 = rlarrn();

        const res = solve(l1, l2);
        cl(res);
    }
}

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

let inStr = '';
let curLine = 0;
const cl = console.log;

process.stdin.on('data', function(inStdin) {inStr += inStdin;});
process.stdin.on('end', function() {inStr = inStr.split('\n');main();});

function readline() {return inStr[curLine++].replace(/\s+$/g, '');}
function rlsn() {return Number(readline());}
function rlarrstr() {return readline().split(' ');}
function rlarrn() {return rlarrstr().map(Number);}
function makeFreqMap(str) {const m={};for (let char of str) m[char]=m[char]+1||1;return m;}

const readline = require('readline')

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

function solve(l, r, x, a, b) {
    if (a === b) return 0
    if (b >= a + x || b <= a - x) return 1
    if (b < a) {
        if (a + x <= r || b - x >= l) return 2
        if (a - x >= l && b + x <= r) return 3
        return -1
    } else {
        if (a - x >= l || b + x <= r) return 2
        if (a + x <= r && b - x >= l) return 3
        return -1
    }
}

var numOfCases = Number(readline());

for (var testCase = 0; testCase < numOfCases; testCase++) {
    var firstLine = readline().split(' ').map(Number);
    var l = firstLine[0];
    var r = firstLine[1];
    var x = firstLine[2];

    var secondLine = readline().split(' ').map(Number);
    var a = secondLine[0];
    var b = secondLine[1];

    var result = process(l, r, x, a, b);
    print(result);
}

function process(l, r, x, a, b) {
    if (a === b) {
        return 0
    }

    if (Math.abs(l - r) < x) {
        return -1;
    }

    if (Math.abs(a - b) >= x) {
        return 1;
    }

    if (a > b) {
        var tmp = a;
        a = b;
        b = tmp;
    }

    if (r - b >= x || a - l >= x) {
        return 2;
    }

    if (r - a >= x && b - l >= x) {
        return 3;
    }

    return -1;
}

'use strict';

var fs = require('fs');

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

var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const [l, r, x] = rns(),
        [a, b] = rns();
  if (a === b) return 0;
  if (Math.abs(a - b) >= x) return 1;
  if (a - l < x && r - a < x) return -1;
  if (b - l < x && r - b < x) return -1;
  if (a - l > x) {
    if (b - l > x) return 2;
  }
  if (r - a > x) {
    if (r - b > x) return 2;
  }
  return 3;
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      let s = solve(r);
      if (s === undefined) s = '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

const inputs = fs__default["default"].readFileSync(0, 'utf-8').split(/\r?\n/);
void function () {
  const read = ((i = 0) => () => inputs[i++])();
  const output = main(read);
  process.stdout.write(output);
}();


function splitInput(i) {
    return i.split('\n')
}

function splitLine(l) {
    return l.split(' ').map((e) => +e)
}

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

let input = ''

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

process.stdin.on('end', () => {
    const lines = splitInput(input.trim())
    run(lines.map((l) => splitLine(l)))
})

function output(o) {
    process.stdout.write(`${o}\n`)
}

function run(lines) {
    let iterator = 0
    let [n, m] = lines[iterator++]
    const inDegrees = Array(n + 1).fill(0)
    inDegrees[0] = null
    let nodesWithInDegreeZero = n

    while (m > 0) {
        --m
        const [nodeA, nodeB] = lines[iterator++]
        const minNode = Math.min(nodeA, nodeB)
        if (inDegrees[minNode] === 0) {
            --nodesWithInDegreeZero
        }
        ++inDegrees[minNode]
    }

    let [q] = lines[iterator++]
    while (q > 0) {
        --q
        const [type, nodeA, nodeB] = lines[iterator++]
        switch (type) {
            case 1: {
                const minNode = Math.min(nodeA, nodeB)
                if (inDegrees[minNode] === 0) {
                    --nodesWithInDegreeZero
                }
                ++inDegrees[minNode]
            }
                break
            case 2: {
                const minNode = Math.min(nodeA, nodeB)
                if (inDegrees[minNode] === 1) {
                    ++nodesWithInDegreeZero
                }
                --inDegrees[minNode]
            }
                break
            case 3: {
                output(nodesWithInDegreeZero)
            }
        }
    }
}

const main = () => {

	var n, m;
	var _in = readIntArr();
	n = _in[0];
	m = _in[1];
	var maxCnts = n;
	var largerCnts = [];
	for (var i = 0; i < n + 1; i++) {
		largerCnts.push(0);
	}
	for (var _ = 0; _ < m; _++) {
		_in = readIntArr();
		var u = _in[0];
		var v = _in[1];
		if (u > v) {
			var temp = v;
			v = u;
			u = temp;
		}
		if (++largerCnts[u] === 1) {
			maxCnts--;
		}
	}

	var q = readInt();
	var allans = [];
	for (var _ = 0; _ < q; _++) {
		_in = readIntArr();
		if (_in.length === 1) { // 3
			allans.push(maxCnts);
			continue;
		}
		var x, u, v;
		x = _in[0];
		u = _in[1];
		v = _in[2];
		if (u > v) {
			var temp = v;
			v = u;
			u = temp;
		}
		if (x === 2) {
			if (--largerCnts[u] === 0) {
				maxCnts++;
			}
		} else { // x === 1
			if (++largerCnts[u] === 1) {
				maxCnts--;
			}
		}
	}
	multiLineArrayPrint(allans);

	return;
}

const readInt = () => parseInt(readline());
const readString = () => readline();
const readIntArr = () => readline().split(" ").map(zzzz => parseInt(zzzz));
const parseLong = (string) => { // javascript's largest long is < (1<<62)
	var n = string.length;
	var res = 0;
	for (var i = 0; i < n; i++) {
		res *= 10;
		res += parseInt(string[i]);
	}
	return res;
}
const readLong = () => parseLong(readLong());
const readLongArr = () => readline().split(" ").map(zzzz => parseLong(zzzz));
const oneLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join(' '));
const multiLineArrayPrint = (arr) => print(arr.map(zzzz => zzzz.toString()).join('\n'));
const multiLineArrayOfArraysPrint = (arr) => print(arr.map(yyyy => yyyy.map(zzzz => zzzz.toString()).join(' ')).join('\n'));
const makeArr = (defaultVal, dimensionsArr) => {
	var n = dimensionsArr.length;
	if (n === 1) return Array(dimensionsArr[0]).fill(defaultVal);
	else {
		var temp = [];
		for (var i = 0; i < dimensionsArr[0]; i++)
			temp.push(makeArr(defaultVal, dimensionsArr.slice(1)));
		return temp;
	}
}

for (_ = 0; _ < 1; _++) {
	main();
}

// newline for testing
 //newline for testing
// codeforces js cannot use "let" keyword. use "var" instead
// codeforces js cannot destructure arrays

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function printline(s, end = "\n") {
  process.stdout.write(s + end);
}

let alive = 0;
const under = [];
const upper = [];

function main() {
  const [n, m] = readline().split(' ').map((rl) => parseInt(rl, 10));;

  for (let i = 0; i <= n; ++i) {
    upper.push(0);
    under.push(0);
  }
  alive = n;

  for (let i = 1; i <= m; ++i) {
    const [u, v] = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (upper[Math.min(u, v)] === 0) alive--;
    upper[Math.min(u, v)]++;
    under[Math.max(u, v)]++;
  }

  let q = parseInt(readline(), 10);
  while (q--) {
    const query = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (query.length === 1) {
      printline(alive);
    } else {
      const u = query[1];
      const v = query[2];
      if (query[0] === 1) {
        if (upper[Math.min(u, v)] === 0) alive--;
        upper[Math.min(u, v)]++;
        under[Math.max(u, v)]++;
      } else {
        upper[Math.min(u, v)]--;
        if (upper[Math.min(u, v)] === 0) alive++;
        under[Math.max(u, v)]--;
      }
    }

  }

}

// run: cat input.txt | node C.js

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function main() {
  const [n, m] = readline().split(' ').map(x => parseInt(x));
  const deg = [];
  for(let i = 0; i < n; i++) {
    deg.push(0)
  }
  for(let i = 0; i < m; i++) {
    const [u, v] = readline().split(' ').map(x => parseInt(x));
    deg[Math.min(u-1, v-1)]++;
  }
  let ans = 0
  for(let i = 0; i < n; i++) {
    if(deg[i] === 0) {
      ans++;
    }
  }
  const show = (deg) => console.log(...deg)
  const q = parseInt(readline())
  for(let i = 0; i < q; i++) {
    const query = readline().split(' ').map(x => parseInt(x));
    if(query[0] === 3) {
      console.log(ans)
    } else {
      const who = Math.min(query[1]-1, query[2]-1)
      if(query[0] === 1) {
        deg[who]++;
        if(deg[who] === 1) {
          ans--
        }
      } else {
        deg[who]--;
        if(deg[who] === 0) {
          ans++
        }
      }
    }
  }
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

var maxN = 2 * 1e5 + 10
var mod = 1e9 + 7

function main() {
  // Array(Number(xx)).fill(1).map((t, i) => {
  var [n, m] = readline().split(' ').map((x, iii) => {
    return parseInt(x)
  })
  var a = new Array(n)
  // for (let i = 0; i <; i++) {
  //
  // }
  var alive = new Array(n).fill(true)
  var willDie = new Array(n).fill(false)
  var count = new Array(n).fill(0)
  for (let i = 0; i < m; i++) {
    var [u, v] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    if (u > v) {
      var swap = u
      u = v
      v = swap
    }

    u--
    v--
    willDie[Math.min(u, v)] = true
    count[u]++
  }
  var res = 0
  for (let i = 0; i < n; i++) {
    if (!willDie[i]) res++
  }
  var q = parseInt(readline());

  for (let i = 0; i < q; i++) {
    var [req, u, v] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    u--
    v--

    if (u > v) {
      var swap = u
      u = v
      v = swap
    }
    if (req === 3) {
      console.log(res)
    }
    if (req === 2) {
      count[u]--
      if (count[u] === 0) res++
    }
    if (req === 1) {
      count[u]++
      if (count[u] === 1) res--
    }
  }
  // })
  // var res = new Array(n)
}

function plus(a, b, res) {
// console.log(a, b, res)
  if (a === 0) return res

  return plus(a < 0 ? a + 1 : a - 1, b, a < 0 ? res - b : res + b)
}

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

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

function main () {
	const [n, m] = rna();

	const deg = Array(n+1).fill(0);
	for (let i = 0; i < m; i++) {
		const [u, v] = rna();
		++deg[Math.min(u, v)];
	}

	let ans = 0;
	for (let u = 1; u <= n; u++) {
		ans += deg[u] == 0
	}

	let q = rn();
	while (q--) {
		const [op, u, v] = rna();

		if (op == 1) {
			if (++deg[Math.min(u, v)] == 1) ans--;
		} else if (op == 2) {
			if (--deg[Math.min(u, v)] == 0) ans++;
		} else {
			console.log(ans);
		}
	}
}

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

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

function main () {
	const [n, m] = rna();
	const adj = Array.from(Array(n+1), x => []);
	const cnt = Array(n+1).fill(0);
	for (let i = 0; i < m; i++) {
		let [u, v] = rna();
		adj[u].push(v);
		adj[v].push(u);
		++cnt[Math.min(u, v)];
	}

	let ans = 0;
	for (let u = 1; u <= n; u++) {
		ans += cnt[u] == 0
	}

	let q = rn();
	while (q--) {
		let [type, u, v] = rna();

		if (type == 1) {
			if (++cnt[Math.min(u, v)] == 1) {
				ans--;
			}
		} else if (type == 2) {
			if (--cnt[Math.min(u, v)] == 0) {
				ans++;
			}
		} else {
			console.log(ans);
		}
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function printline(s, end = "\n") {
  process.stdout.write(s + end);
}

let alive = 0;
const under = [];
const upper = [];

function main() {
  const [n, m] = readline().split(' ').map((rl) => parseInt(rl, 10));;

  for (let i = 0; i <= n; ++i) {
    upper.push(0);
    under.push(0);
  }
  alive = n;

  for (let i = 1; i <= m; ++i) {
    const [u, v] = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (upper[Math.min(u, v)] === 0) alive--;
    upper[Math.min(u, v)]++;
    under[Math.max(u, v)]++;
  }

  let q = parseInt(readline(), 10);
  while (q--) {
    const query = readline().split(' ').map((rl) => parseInt(rl, 10));
    if (query.length === 1) {
      printline(alive);
    } else {
      const u = query[1];
      const v = query[2];
      if (query[0] === 1) {
        if (upper[Math.min(u, v)] === 0) alive--;
        upper[Math.min(u, v)]++;
        under[Math.max(u, v)]++;
      } else {
        upper[Math.min(u, v)]--;
        if (upper[Math.min(u, v)] === 0) alive--;
        under[Math.max(u, v)]--;
      }
    }

  }

}

// run: cat input.txt | node C.js


function getNearestNotNofiedStudent(students) {
    for (var i = 0; i < students.length; i++) {
        if (students[i].notified === false) {
            return students[i];
        }
    }

    return null;
}

function run(students) {
    // print('hello!');

    students = students.map(function (student) {
        student.notified = false;
        return student;
    });

    var polikarp = students[0];

    polikarp.notified = true;

    if (polikarp.limit === 0) {
        // print('polikarp');
        return -1;
    }

    var overallLimit = students.reduce(function (acc, student) {
       return acc + student.limit;
    }, 0);

    if (students.length > overallLimit + 1) {
        // print('students');
        return -1;
    }

    students = students.sort(function (left, right) {
        if (left.notified) {
            return -1;
        }

        if (right.notified) {
            return 1;
        }

        if (left.limit === right.limit) {
            return 0;
        }

        return left.limit < right.limit ? 1 : -1;
    });

    var messages = [];

    for (var i = 0; i < students.length; i++) {
        var currentStudent = students[i];
        while (currentStudent.limit > 0) {
            var notNotifiedStudent = getNearestNotNofiedStudent(students);
            if (notNotifiedStudent === null) {
                break;
            }
            notNotifiedStudent.notified = true;
            currentStudent.limit--;
            messages.push({
                from: currentStudent.number,
                to: notNotifiedStudent.number
            });
        }
    }

    return (
        messages.length + "\n" +
        messages.reduce(function (acc, message) {
            return acc + message.from + ' ' + message.to + "\n";
        }, '')
    );
}

var count = readline();
var students = readline()
    .split(' ')
    .map(function (a) { return parseInt(a); })
    .map(function (limit, number) {
        return { limit: limit, number: number + 1 };
    });

var result = run(students);
print(result);

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });

  if ((+canSend + +procof) < +(col-1)) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  print(numbers.length -1);
  numbers.slice(1).forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

readline();

var tmp_i = 1;
var maxes = readline().split(' ').map(function(x){

    return [tmp_i++, parseInt(x)];
});
var queue = [maxes.shift()];
var log = [];

maxes.sort(function(a, b){

    return b[1] - a[1];
});

while (queue.length > 0) {

    var std = queue[0][0];
    var cap = queue[0][1];

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

        if(maxes.length > 0) {
            log.push([std, maxes[0][0]]);
            queue.push(maxes.shift());
        }
        else
            break;
    }

    queue.shift();
}

if(maxes.length === 0) {

    print(log.length);
    for(var i = 0; i < log.length; i++)
        print(log[i].join(' '));
} else
    print(-1);

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;
if (!peoples[0].available && peoples.length > 1) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  var max = 0;
  var ind = -1;

  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow && peoplesArr[i].available >=max) {
      max = peoplesArr[i].available;
      ind = i;
    }
  }
  return ind;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0 && peoplesArr[i].isKnow) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return true;
    }
  }
  return false;
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    if (!say(result, peoplesArr, unknownIndex)) {
      print(-1);
      return;
    }
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

/*
readline()
print
*/

var iamdone = false;
var strings = [];
var n = +((readline() + "").trim());
var a = (readline() + "").trim().split(" ");
a = a.map((v, i) => {
    return {
        i: i + 1,
        v: +v,
        c: false
    }
}).sort(function(a, b){
    if(a.v > b.v) return -1; else return 1;
    return 0;
});

for(var i = 0; i < n; i++){
    if(a[i].i === 1){
        if(a[i].v === 0){
            iamdone = true;
        }else{
            a[i].v--;
            a[i].c = true;
        }
        break;
    }
}

if(iamdone){
    print("-1");
}else{
    if(a[0].i == 1){
        a[1].c = true;
        strings[strings.length] = "1 " + a[1].i;
    }else{
        a[0].c = true;
        strings[strings.length] = "1 " + a[0].i;
    }

    var link1 = 0;
    var link2 = 0;

    while(true){
        if(a[link1].v > 0 && a[link2].c === false){
            a[link1].v--;
            a[link2].c = true;
            strings[strings.length] = a[link1].i + " " + a[link2].i;
            link2++;
        }else if(a[link1].v <= 0){
            link1++;
        }else if(a[link2].c === true){
            link2++;
        }

        if(!a[link1] || !a[link2]){
            break;
        }
    }

    var error = false;

    for(var i = 0; i < n; i++){
        if(a[i].c === false){
            error = true;
            break;
        }
    }

    if(error){
        print("-1");
    }else{
        print(strings.length);
        for(var i = 0; i < strings.length; i++){
            print(strings[i]);
        }
    }

}

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });

  if (+canSend < +col-1) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  numbers = numbers.slice(1).sort((a, b) => a[2] - b[2]);
  print(numbers.length);
  numbers.forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });

  if (+canSend < +col-1) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  print(numbers.length);
  numbers.slice(1).forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;
  nums = nums.slice(1).map(function (x, i) {
    canSend += +x;
    return [+x, i+2, 0];
  });
  if (+canSend < +col) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  numbers = numbers.slice(1).sort((a, b) => a[2] - b[2]);
  print(numbers.length);
  numbers.forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

function main() {
  var col = +readline();
  var nums = readline().split(" ");
  var procof = nums[0];
  if (procof < 1) {
    print(-1);
    return 0;
  }
  var canSend = 0;

  nums = nums.slice(1).map(function (x, i) {
    canSend += x;
    return [+x, i+2, 0];
  });
  if (canSend < col) {
    print(-1);
    return 0;
  }
  nums.sort((a, b) => b[0] - a[0]);
  var numbers = [[procof, 1], ...nums];

  var next = 1;
  for (var i = 0; i < col; ++i) {
    var mes = +numbers[i][0];
    for (var j = next; j < next + mes; ++j) {
      if (numbers[j]) numbers[j][2] = numbers[i][1];
    }
    next += mes;
  }

  numbers = numbers.slice(1).sort((a, b) => a[2] - b[2]);
  print(numbers.length);
  numbers.forEach(number => print(number[2] + " " + number[1]));

  return 0;
}

main();

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;

if (!peoples[0].available) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return;
    }
  }
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    say(result, peoplesArr, unknownIndex);
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;
if (!peoples[0].available) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return true;
    }
  }
  return false;
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    if (!say(result, peoplesArr, unknownIndex)) {
      print(-1);
      return;
    }
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;

calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return;
    }
  }
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    say(result, peoplesArr, unknownIndex);
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

var peoplesCount = readline();
var peoples = readline()
  .split(' ')
  .map(function(count) {
    return { available: count };
  });

peoples[0].isKnow = true;
if (!peoples[0].available) print(-1);
else calculate(peoples);

function getUnknownIndex(peoplesArr) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (!peoplesArr[i].isKnow) return i;
  }
  return -1;
}

function say(resultArray, peoplesArr, unknownPeopleIndex) {
  for (var i = 0; i < peoplesArr.length; i++) {
    if (peoplesArr[i].available > 0 && peoplesArr[i].isKnow) {
      peoplesArr[i].available--;
      peoplesArr[unknownPeopleIndex].isKnow = true;
      resultArray.push([ i+1, unknownPeopleIndex + 1 ]);
      return true;
    }
  }
  return false;
}

function calculate(peoplesArr) {
  var result = [];
  for (var i = 0; i < peoplesArr.length - 1; i++ ) {
    var unknownIndex = getUnknownIndex(peoplesArr);
    if (unknownIndex == -1) {
      print(-1);
      return;
    }
    if (!say(result, peoplesArr, unknownIndex)) {
      print(-1);
      return;
    }
  }
  print(result.length);
  result.forEach(function(item) {
    print(item.join(' '));
  })
}

/*
readline()
print
*/

var iamdone = false;
var strings = [];
var n = +((readline() + "").trim());
var a = (readline() + "").trim().split(" ");
a = a.map((v, i) => {
    return {
        i: i + 1,
        v: v,
        c: false
    }
}).sort(function(a, b){
    if(a.v > b.v) return -1; else return 1;
    return 0;
});

for(var i = 0; i < n; i++){
    if(a[i].i === 1){
        if(a[i].v === 0){
            iamdone = true;
        }else{
            a[i].v--;
            a[i].c = true;
        }
    }
}

if(iamdone){
    print("-1");
}else{
    if(a[0].i == 1){
        a[1].c = true;
        strings[strings.length] = "1 " + a[1].i;
    }else{
        a[0].c = true;
        strings[strings.length] = "1 " + a[0].i;
    }

    var link1 = 0;
    var link2 = 0;

    while(true){
        if(a[link1].v > 0 && a[link2].c === false){
            a[link1].v--;
            a[link2].c = true;
            strings[strings.length] = a[link1].i + " " + a[link2].i;
            link2++;
        }else if(a[link1].v <= 0){
            link1++;
        }else if(a[link2].c === true){
            link2++;
        }

        if(!a[link1] || !a[link2]){
            break;
        }
    }

    var error = false;

    for(var i = 0; i < n; i++){
        if(a[i].c === false){
            error = true;
            break;
        }
    }

    if(error){
        print("-1");
    }else{
        print(strings.length);
        for(var i = 0; i < strings.length; i++){
            print(strings[i]);
        }
    }

}

/*
readline()
print
*/

var iamdone = false;
var strings = [];
var n = +((readline() + "").trim());
var a = (readline() + "").trim().split(" ").map((v, i) => {
    var c = false;
    if(i === 0){
        v--;
        c = true;
        if(v < 0) iamdone = true;
    }
    return {
        i: i + 1,
        v: v,
        c: c
    }
}).sort(function(a, b){
    if(a.v > b.v) return -1; else return 1;
    return 0;
});

if(iamdone){
    print("-1");
}else{
    a[0].c = true;
    strings[strings.length] = "1 " + a[0].i;

    var link1 = 0;
    var link2 = 0;

    while(true){
        if(a[link1].v > 0 && a[link2].c === false){
            a[link1].v--;
            a[link2].c = true;
            strings[strings.length] = a[link1].i + " " + a[link2].i;
            link2++;
        }else if(a[link1].v <= 0){
            link1++;
        }else if(a[link2].c === true){
            link2++;
        }

        if(!a[link1] || !a[link2]){
            break;
        }
    }

    var error = false;

    for(var i = 0; i < n; i++){
        if(a[i].c === false){
            error = true;
            break;
        }
    }

    if(error){
        print("-1");
    }else{
        print(strings.length);
        for(var i = 0; i < strings.length; i++){
            print(strings[i]);
        }
    }

}

function getNearestNotNofiedStudent(students) {
    for (var i = 0; i < students.length; i++) {
        if (students[i].notified === false) {
            return students[i];
        }
    }

    return null;
}

function run(students) {
    // print('hello!');

    students = students.map(function (student) {
        student.notified = false;
        return student;
    });

    var polikarp = students[0];

    polikarp.notified = true;

    if (polikarp.limit === 0) {
        // print('polikarp');
        return -1;
    }

    var overallLimit = students.reduce(function (acc, student) {
       return acc + student.limit;
    }, 0);

    if (students.length > overallLimit + 1) {
        // print('students');
        return -1;
    }

    students = students.sort(function (left, right) {
        if (left.notified) {
            return -1;
        }

        if (right.notified) {
            return 1;
        }

        if (left.limit === right.limit) {
            return 0;
        }

        return left.limit < right.limit ? 1 : -1;
    });

    var messages = [];

    for (var i = 0; i < students.length; i++) {
        var currentStudent = students[i];
        while (currentStudent.limit > 0) {
            var notNotifiedStudent = getNearestNotNofiedStudent(students);
            if (notNotifiedStudent === null) {
                break;
            }
            notNotifiedStudent.notified = true;
            currentStudent.limit--;
            messages.push({
                from: currentStudent.number,
                to: notNotifiedStudent.number
            });
        }
    }

    return messages.reduce(function (acc, message) {
        return acc + message.from + ' ' + message.to + "\n";
    }, '');
}

var count = readline();
var students = readline()
    .split(' ')
    .map(function (a) { return parseInt(a); })
    .map(function (limit, number) {
        return { limit: limit, number: number + 1 };
    });

var result = run(students);
print(result);


function main() {
  var input = readline().split(' ').map(Number)
  var n = input[0]
  var k = input[1]

  var need = readline().split(' ').map(Number)
  var have = readline().split(' ').map(Number)

  var l = 0
  var r = Math.pow(10, 9) * 2 + 1

  function canPrepare(c) {
    var total = 0

    for (var i = 0; i < need.length; i++) {
      total += Math.max(need[i] * c - have[i], 0)

      if (total > k) return false
    }

    return true
  }

  while (l + 1 < r) {
    var m = Math.round((l + r) / 2)
    if (canPrepare(m)) {
      l = m
    } else {
      r = m
    }
  }

  print(l)

  return 0
}

main()

var k = readline().split()[1];
var a = readline().split();
var b = readline().split();

function canWeMake(x, a, b, k) {
	for (var i=0; i<a.length; i++) {
		var y = x * a[i];
		var z = y - b[i];
		if (z >= 0) {
			k -= z;
		}
	}
	return k;
}

function f(k, a, b) {
	var max = 0;
	var l = 0;
	var r = 2 * Math.pow(10, 9);
	while (l <= r) {
		var n = Math.floor((r + l) / 2);

		var res = canWeMake(n, a, b, k);

		if (res == 0) {
			return n;
		}

		if (res > 0) {
			max = Math.max(max, n);
			if (l == r) {
				return max;
			}
			l = n + 1;
		}
		else {
			if (l == r) {
				return max;
			}
			r = n;
		}
	}
	return max;
}

var res = f(k, a, b);

print(res);

//f(3, [4,3,5,6], [11,12,14,20]);

var k = readline().split()[1];
var a = readline().split();
var b = readline().split();

function canWeMake(x, a, b, k) {
	for (var i=0; i<a.length; i++) {
		var y = x * a[i];
		var z = y - b[i];
		if (z >= 0) {
			k -= z;
		}
	}
	return k;
}

function f(k, a, b) {
	var max = 0;
	var l = 0;
	var r = 2 * Math.pow(10, 9);
	while (l < r) {
		var n = Math.floor((r + l) / 2);

		var res = canWeMake(n, a, b, k);

		if (res < 0) {
			r = n;
		}
		else if (res > 0) {
			max = Math.max(max, n);
			l = n + 1;
		} else {
			return n;
		}
	}
	return max;
}

var res = f(k, a, b);

print(res);

//f(3, [4,3,5,6], [11,12,14,20]);

function main() {
  var input = readline().split(' ').map(Number)
  var n = input[0]
  var k = input[1]

  var need = readline().split(' ').map(Number)
  var have = readline().split(' ').map(Number)

  var l = 0
  var r = Math.pow(10, 9) * 2 + 1

  function canPrepare(c) {
    var total = 0

    for (var i = 0; i < need.length; i++) {
      total += need[i] * c - have[i]

      if (total > k) return false
    }

    return true
  }

  while (l + 1 < r) {
    var m = Math.round((l + r) / 2)

    if (canPrepare(m)) {
      l = m
    } else {
      r = m
    }
  }

  print(l)

  return 0
}

main()