Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of $$$n$$$ distinct integers. An array $$$b = [b_1, b_2, \ldots, b_k]$$$ is called nice if for any two distinct elements $$$b_i, b_j$$$ of $$$b$$$, $$$|b_i-b_j|$$$ appears in $$$b$$$ at least once. In addition, all elements in $$$b$$$ must be distinct. Can you add several (maybe, $$$0$$$) integers to $$$a$$$ to create a nice array $$$b$$$ of size at most $$$300$$$? If $$$a$$$ is already nice, you don't have to add any elements.For example, array $$$[3, 6, 9]$$$ is nice, as $$$|6-3|=|9-6| = 3$$$, which appears in the array, and $$$|9-3| = 6$$$, which appears in the array, while array $$$[4, 2, 0, 6, 9]$$$ is not nice, as $$$|9-4| = 5$$$ is not present in the array.For integers $$$x$$$ and $$$y$$$, $$$|x-y| = x-y$$$ if $$$x > y$$$ and $$$|x-y| = y-x$$$ otherwise.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \leq t \leq 50$$$), the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \cdots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$) — the elements of the array $$$a$$$.

For each test case, output one line containing YES if Omkar can create a nice array $$$b$$$ by adding elements to $$$a$$$ and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted. If the first line is YES, output a second line containing a single integer $$$k$$$ ($$$n \leq k \leq 300$$$).  Then output one line containing $$$k$$$ distinct integers $$$b_1, b_2, \cdots, b_k$$$ ($$$-10^9 \leq b_i \leq 10^9$$$), the elements of the nice array $$$b$$$. $$$b_1, b_2, \cdots, b_k$$$ can be in any order. For each $$$a_i$$$ in $$$a$$$, $$$a_i$$$ must appear at least once in $$$b$$$. It can be proved that if Omkar can create such an array $$$b$$$, then he can also do so in a way that satisfies the above constraints. If multiple solutions exist, you can print any.

(function () {
    var defines = {};
    var entry = [null];
    function define(name, dependencies, factory) {
        defines[name] = { dependencies: dependencies, factory: factory };
        entry[0] = name;
    }
    define("require", ["exports"], function (exports) {
        Object.defineProperty(exports, "__cjsModule", { value: true });
        Object.defineProperty(exports, "default", { value: function (name) { return resolve(name); } });
    });
    var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
        function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
        return new (P || (P = Promise))(function (resolve, reject) {
            function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
            function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
            function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
            step((generator = generator.apply(thisArg, _arguments || [])).next());
        });
    };
    var __generator = (this && this.__generator) || function (thisArg, body) {
        var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
        return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f) throw new TypeError("Generator is already executing.");
            while (_) try {
                if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
                if (y = 0, t) op = [op[0] & 2, t.value];
                switch (op[0]) {
                    case 0: case 1: t = op; break;
                    case 4: _.label++; return { value: op[1], done: false };
                    case 5: _.label++; y = op[1]; op = [0]; continue;
                    case 7: op = _.ops.pop(); _.trys.pop(); continue;
                    default:
                        if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                        if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                        if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                        if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                        if (t[2]) _.ops.pop();
                        _.trys.pop(); continue;
                }
                op = body.call(thisArg, _);
            } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
            if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
        }
    };
    define("utils/readline", ["require", "exports"], function (require, exports) {
        "use strict";
        exports.__esModule = true;
        exports.getLineReader = exports.getAllLines = void 0;
        function getAllLines() {
            return new Promise(function (res) {
                var inputText = "";
                process.stdin.on("data", function (data) { return (inputText += data); });
                process.stdin.on("end", function () {
                    var EOL = require("os").EOL;
                    res(inputText.split(EOL));
                });
            });
        }
        exports.getAllLines = getAllLines;
        function getLineReader() {
            return __awaiter(this, void 0, void 0, function () {
                var lines, lineNumber;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, getAllLines()];
                        case 1:
                            lines = _a.sent();
                            lineNumber = 0;
                            return [2 /*return*/, {
                                    nextLine: function () {
                                        var _a;
                                        return (_a = lines[lineNumber++]) !== null && _a !== void 0 ? _a : "";
                                    }
                                }];
                    }
                });
            });
        }
        exports.getLineReader = getLineReader;
    });
    define("1536/index", ["require", "exports", "utils/readline"], function (require, exports, readline_1) {
        "use strict";
        exports.__esModule = true;
        (function () { return __awaiter(void 0, void 0, void 0, function () {
            var lr, testCases, N, line, arr, result, i;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, readline_1.getLineReader()];
                    case 1:
                        lr = _a.sent();
                        testCases = parseInt(lr.nextLine(), 10);
                        while (testCases--) {
                            N = parseInt(lr.nextLine(), 10);
                            line = lr.nextLine();
                            arr = line
                                .trim()
                                .split(" ")
                                .map(function (v) { return parseInt(v, 10); });
                            if (arr.some(function (v) { return v < 0; })) {
                                console.log("NO");
                            }
                            else {
                                result = [];
                                for (i = 0; i <= 100; i++) {
                                    result.push(i);
                                }
                                console.log("YES");
                                console.log(101);
                                console.log.apply(console, result);
                            }
                        }
                        return [2 /*return*/];
                }
            });
        }); })();
    });

    'marker:resolver';

    function get_define(name) {
        if (defines[name]) {
            return defines[name];
        }
        else if (defines[name + '/index']) {
            return defines[name + '/index'];
        }
        else {
            var dependencies = ['exports'];
            var factory = function (exports) {
                try {
                    Object.defineProperty(exports, "__cjsModule", { value: true });
                    Object.defineProperty(exports, "default", { value: require(name) });
                }
                catch (_a) {
                    throw Error(['module "', name, '" not found.'].join(''));
                }
            };
            return { dependencies: dependencies, factory: factory };
        }
    }
    var instances = {};
    function resolve(name) {
        if (instances[name]) {
            return instances[name];
        }
        if (name === 'exports') {
            return {};
        }
        var define = get_define(name);
        instances[name] = {};
        var dependencies = define.dependencies.map(function (name) { return resolve(name); });
        define.factory.apply(define, dependencies);
        var exports = dependencies[define.dependencies.indexOf('exports')];
        instances[name] = (exports['__cjsModule']) ? exports["default"] : exports;
        return instances[name];
    }
    if (entry[0] !== null) {
        return resolve(entry[0]);
    }
})();

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var isOK = true;
		var max = 0;
		for(var i = 0; i < N; i++){
			if(list[i] < 0){
				isOK = false;
			}
			max = Math.max(max, list[i]);
		}
		if(!isOK){
			myout("No");
			continue;
		}
		list.sort(function(a,b){
			return a - b;
		});
		for(var i = 0; i < max; i++){
			if(list.indexOf(i) == -1){
				list.push(i);
			}
		}

		myout("Yes");
		myout(list.length);
		myout(myconv(list, 8));
	}
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

var ARR = [];
for (var i = 0; i < 101; i++) {
   ARR.push(i);
}
var ans = ARR.join(' ');

function solve() {
   read();
   var hasLessZero = false;
   var arr = readArray((x) => {
      if (Number(x) < 0) {
         hasLessZero = true;
      }
   });
   if (hasLessZero) {
      write('no');
      return;
   }
   write('yes');
   write(101);
   write(ans);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

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

// https://codeforces.com/contest/1536/problem/D
// import { readline, print } from "@ip-algorithmics/codeforces-io";
var testCases = parseInt(readline(), 10);
while (testCases--) {
  var N = parseInt(readline(), 10);
  var line = readline();
  var arr = line
    .trim()
    .split(" ")
    .map((v) => parseInt(v, 10));
  if (arr.some((v) => v < 0)) {
    print("NO");
  } else {
    var result = [];
    for (var i = 0; i <= 100; i++) {
      result.push(i);
    }
    print("YES");
    print(101);
    print(...result);
  }
}

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

function main() {
  var testCasesNum = +readline();

  for (var i = 0; i < testCasesNum; i++) {
    var n = +readline();
    var nums = readNumArray();
    var max = 0;
    var isNegative = false;
    for (var j = 0; j < n; j++) {
      if (nums[j] < 0) {
        isNegative = true;
        break;
      }
      if (nums[j] > max) {
        max = nums[j];
      }
    }
    if (isNegative) {
      print('No');
    } else {
      print('Yes');
      print(String(max + 1));
      var result = '0';
      for (var j = 1; j < max + 1; j++) {
        result = result + ' ' + String(j);
      }
      print(result);
    }
  }
}

main();

(()=>{"use strict";var e={59:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function u(e){try{s(r.next(e))}catch(e){i(e)}}function a(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(u,a)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,u={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;u;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,r=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!((o=(o=u.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){u=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){u.label=i[1];break}if(6===i[0]&&u.label<o[1]){u.label=o[1],o=i;break}if(o&&u.label<o[2]){u.label=o[2],u.ops.push(i);break}o[2]&&u.ops.pop(),u.trys.pop();continue}i=t.call(e,u)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(230);r(void 0,void 0,void 0,(function(){var e,t,n,r,u,a;return o(this,(function(o){switch(o.label){case 0:return e=i.getLineReader(),n=parseInt,[4,e.nextLine()];case 1:t=n.apply(void 0,[o.sent(),10]),o.label=2;case 2:return t--?(r=parseInt,[4,e.nextLine()]):[3,5];case 3:return r.apply(void 0,[o.sent(),10]),[4,e.nextLine()];case 4:if(o.sent().trim().split(" ").map((function(e){return parseInt(e,10)})).some((function(e){return e<0})))console.log("NO");else{for(u=[],a=0;a<=100;a++)u.push(a);console.log("YES"),console.log(101),console.log.apply(console,u)}return[3,2];case 5:return[2]}}))}))},230:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getLineReader=void 0;var o=r(n(58));function i(){var e=o.default.createInterface({input:process.stdin,output:process.stdout,terminal:!1});return{nextLine:function(){return new Promise((function(t,n){e.resume(),e.on("line",(function(n){e.pause(),t(n)}))}))},close:function(){e.close()}}}t.getLineReader=i,t.default=i},58:e=>{e.exports=require("readline")}},t={};!function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,n),i.exports}(59)})();

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var isOK = true;
		var max = 0;
		for(var i = 0; i < N; i++){
			if(list[i] < 0){
				isOK = false;
			}
			max = Math.max(max, list[i]);
		}
		if(!isOK){
			myout("No");
			continue;
		}
		list.sort(function(a,b){
			return a - b;
		});
		var min = 100000;
		for(var i = 0; i < N - 1; i++){
			min = Math.min(min, list[i + 1] - list[i]);
		}
		for(var i = 1; list.length < 300; i++){
			if(i * min == max){
				break;
			}
			if(list.indexOf(i * min) == -1){
				list.push(i * min);
			}
		}
		myout("Yes");
		myout(list.length);
		myout(myconv(list, 8));
	}
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var isOK = true;
		var max = 0;
		for(var i = 0; i < N; i++){
			if(list[i] < 0){
				isOK = false;
			}
			max = Math.max(max, list[i]);
		}
		if(!isOK){
			myout("No");
			continue;
		}
		list.sort(function(a,b){
			return a - b;
		});
		var min = 100000;
		for(var i = 0; i < N - 1; i++){
			min = Math.min(min, list[i + 1] - list[i]);
		}
		for(var i = 1; list.length < 300; i++){
			if(i * min == max){
				break;
			}
			if(list.indexOf(i * min) == -1){
				list.push(i * min);
			}
		}
		myout(list.length);
		myout(myconv(list, 8));
	}
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var isOK = true;
		for(var i = 0; i < N; i++){
			if(list[i] < 0){
				isOK = false;
				break;
			}
		}
		if(!isOK){
			myout("No");
			continue;
		}
		list.sort(function(a,b){
			return a - b;
		});
		var min = 100000;
		for(var i = 0; i < N - 1; i++){
			min = Math.min(min, list[i + 1] - list[i]);
		}
		for(var i = 1; list.length < 300; i++){
			if(list.indexOf(i * min) == -1){
				list.push(i * min);
			}
		}
		myout(list.length);
		myout(myconv(list, 8));
	}
}

var timer = 0;
function dfs(v, prev) {
   var h = {};
   v.__h = h;
   h.tin = ++timer;
   h.up = [];
   var i = 0;
   var next = prev;
   while (next) {
      h.up[i] = next;
      next = next.__h.up[i++];
   }
   var children = v.childNodes;
   for (i = 0; i < children.length; i++) {
      dfs(children[i], v);
   }
   h.tout = ++timer;
}

function gcd(x, y) {
   if (y === 0) {
      return x;
   }
   return gcd(y, x % y);
}

var ARR = [];
for (var i = 0; i < 101; i++) {
   ARR.push(i);
}
var ans = ARR.join(' ');

function solve() {
   read();
   var hasLessZero = false;
   var arr = readArray((x) => {
      if (Number(x) < 0) {
         hasLessZero = true;
      }
   });
   if (hasLessZero) {
      write('no');
      return;
   }
   write('yes');
   write(ans);
}

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

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

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

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

   var inTextName;
   var outTextName;

   var needWriteFile = false;

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

   if (inTextName) {
      fs.readFile(path.join(__dirname, inTextName), 'utf8', (err, data) => {
         MEMORY = data.split('\r\n');
         init();
         if (needWriteFile) {
            fs.writeFile(path.join(__dirname, outTextName), writeResult, (err) => {
               err ? console.error(err) : console.log('good')
            });
         }
      });
   } else {
      MEMORY = fs.readFileSync(0, 'utf-8').split('\r\n');
      init();
   }
} else {
   init();
}

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Let $$$min(l, r)$$$ be the minimum value among $$$a_l, a_{l + 1}, \ldots, a_r$$$ and $$$max(l, r)$$$ be the maximum value among $$$a_l, a_{l + 1}, \ldots, a_r$$$.Your task is to choose three positive (greater than $$$0$$$) integers $$$x$$$, $$$y$$$ and $$$z$$$ such that:  $$$x + y + z = n$$$;  $$$max(1, x) = min(x + 1, x + y) = max(x + y + 1, n)$$$. In other words, you have to split the array $$$a$$$ into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).Among all such triples (partitions), you can choose any.You have to answer $$$t$$$ independent test cases.

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

For each test case, print the answer: NO in the only line if there is no such partition of $$$a$$$ that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$x + y + z = n$$$) in the second line. If there are several answers, you can print any.

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

"use strict";

const K = 20;

(function () {

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

    let curLine = 0, allLines = [];

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

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

})();

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

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

        let sufMax = [...ara];
        for(let i = n-2; i >= 0; i--) sufMax[i] = Math.max(sufMax[i], sufMax[i+1]);

        let sp = [];
        for(let j = 0; j < K; j++) sp.push([]);

        sp[0] = ara.map(value => value);

        for(let j = 1; j < K; j++) {
            for(let i = 0; i < n; i++) {
                sp[j][i] = sp[j-1][i];
                if(i+(1<<(j-1)) < n) sp[j][i] = Math.min(sp[j][i], sp[j-1][i+(1<<(j-1))]);
            }
        }

        let query = (i, j) => {
            let k = Math.floor(Math.log2(j-i+1));
            return Math.min(sp[k][i], sp[k][j-(1<<k)+1]);
        }

        let mx = 0, flag = false;

        for(let i = 0; i < n-2; i++) {
            mx = Math.max(mx, ara[i]);

            let st = i+1, ed = n;

            while(st+1 < ed) {
                let mid = (st+ed)>>1;

                if(sufMax[mid] > mx) st = mid;
                else ed = mid;
            }

            if(ed == n) continue;
            if(query(i+1, ed-1) != mx && ed < n-1) ed++;

            let rmx = sufMax[ed], mn = query(i+1, ed-1);

            if(mn == mx && mn == rmx) {
                flag = true;

                console.log("YES");
                console.log(`${i+1} ${ed-i-1} ${n-ed}`);

                break;
            }
        }

        if(!flag) console.log("NO");
    }
}

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

let curLine = 0;
let allLines = [];

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

readline.on("close", () => { main() });

let nextLine = () => allLines[curLine++];

const K = 20;

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

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

        let sufMax = [...ara], sufMin = [...ara];

        for(let i = n-2; i >= 0; i--) sufMax[i] = Math.max(sufMax[i], sufMax[i+1]);
        for(let i = n-2; i >= 0; i--) sufMin[i] = Math.min(sufMin[i], sufMin[i+1]);

        let sp = [];
        for(let j = 0; j < K; j++) sp.push([]);

        ara.forEach((element, index) => { sp[0][index] = element; });

        for(let j = 1; j < K; j++) {
            for(let i = 0; i < n; i++) {
                sp[j][i] = sp[j-1][i];
                if(i+(1<<(j-1)) < n) sp[j][i] = Math.min(sp[j][i], sp[j-1][i+(1<<(j-1))]);
            }
        }

        let query = (i, j) => {
            let k = Math.floor(Math.log2(j-i+1));
            return Math.min(sp[k][i], sp[k][j-(1<<k)+1]);
        }

        let mx = 0, flag = false;

        for(let i = 0; i < n-2; i++) {
            mx = Math.max(mx, ara[i]);

            let st = i+1, ed = n;

            while(st+1 < ed) {
                let mid = (st+ed)>>1;

                if(sufMax[mid] > mx) st = mid;
                else ed = mid;
            }

            if(ed == n) continue;
            if(query(i+1, ed-1) != mx && ed < n-1) ed++;

            let rmx = sufMax[ed], mn = query(i+1, ed-1);

            if(mn == mx && mn == rmx) {
                flag = true;

                console.log("YES");
                console.log(`${i+1} ${ed-i-1} ${n-ed}`);

                break;
            }
        }

        if(!flag) console.log("NO");
    }
}


You are given a binary array$$$^{\dagger}$$$ of length $$$n$$$. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a $$$0$$$ into a $$$1$$$ or vice-versa.What is the maximum number of inversions$$$^{\ddagger}$$$ the array can have after performing at most one operation?$$$^\dagger$$$ A binary array is an array that contains only zeroes and ones.$$$^\ddagger$$$ The number of inversions in an array is the number of pairs of indices $$$i,j$$$ such that $$$i<j$$$ and $$$a_i > a_j$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$a_1$$$, $$$a_2$$$,..., $$$a_n$$$ ($$$0 \leq a_i \leq 1$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output a single integer  — the maximum number of inversions the array can have after performing at most one operation.

NoteFor the first test case, the inversions are initially formed by the pairs of indices ($$$1, 2$$$), ($$$1, 4$$$), ($$$3, 4$$$), being a total of $$$3$$$, which already is the maximum possible.For the second test case, the inversions are initially formed by the pairs of indices ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$), being a total of four. But, by flipping the first element, the array becomes $$${1, 1, 0, 0, 1, 0}$$$, which has the inversions formed by the pairs of indices ($$$1, 3$$$), ($$$1, 4$$$), ($$$1, 6$$$), ($$$2, 3$$$), ($$$2, 4$$$), ($$$2, 6$$$), ($$$5, 6$$$) which total to $$$7$$$ inversions which is the maximum possible.

const fs = require("fs");
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
var T = readline();
var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
	var n = readline()-0;
	var a = readline().split(" ").map(w => parseInt(w));
	var pref1 = [];
	var suf0 = [];
	var ans1 = [];
	var ans0 = [];
	for(var i=0;i<n;i++) {
		pref1[i] = (pref1[i-1]||0) + a[i];
		if(!a[i]) ans1[i] = (ans1[i-1]||0) + pref1[i];
		else ans1[i] = (ans1[i-1]||0);
	}
	for(var i=n-1;i>=0;i--) {
		suf0[i] = (suf0[i+1]||0) + (a[i]===0?1:0);
		if(a[i]) ans0[i] = (ans0[i+1]||0) + suf0[i];
		else ans0[i] = (ans0[i+1]||0)
	}
	var ans = ans1[n-1];
	for(var i=0;i<n;i++) {
		if(!a[i]) {
			ans = max(ans, (ans1[n-1]-(pref1[i-1]||0)) + (suf0[i+1]||0))
		} else {
			ans = max(ans, (ans1[n-1]-(suf0[i+1]||0)) + (pref1[i-1]||0))
		}
	}
	console.log(ans);
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var alpha = "abcdefghijklmnopqrstuvwxyz";
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var L = new Array(N + 2).fill(0);
		var R = new Array(N + 2).fill(0);
		for(var i = 0; i < N; i++){
			if(list[i] == 1){
				L[i + 1]++;
			}
			L[i + 1] += L[i];
		}
		for(var i = N - 1; i >= 0; i--){
			if(list[i] == 0){
				R[i + 1]++;
			}
			R[i] += R[i + 1];
		}
		var sum = 0;
		for(var i = 0; i < N; i++){
			if(list[i] == 0){
				sum += L[i];
			}
		}

		var output = sum;
		for(var i = 1; i <= N; i++){
			if(list[i - 1] == 1){
				output = Math.max(output, sum + L[i - 1] - R[i + 1]);
			}else{
				output = Math.max(output, sum - L[i - 1] + R[i + 1]);
			}
		}

		myout(output);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function gcd(a,b )
{
    if (!b)
        return a

    return gcd( b , a%b )
}

function main() {

    let t = parseInt(readLine());

    //let mod = 10**9+7
    loopwhile:
    while(t--)
    {
        let n = parseInt(readLine());

        let arr = readLine().trim().split(" ").map(x=>parseInt(x));

        let countzeros=0
        let countones=0
        let indicefirstzero=-1
        let indicelastone=-1
        let score = 0
        for(let i =0; i<n ;++i)
        {
            if((arr[i]==0)&&(indicefirstzero==-1))
                indicefirstzero=i

            if(arr[i]==1)
                indicelastone=i

            if(arr[i]==0)
                score +=  countones

            countzeros += (arr[i]==0)
            countones += arr[i]&1

        }
        /*console.log("countzeros " + countzeros)
        console.log("countones " + countones)
        console.log("indicelastone " + indicelastone)
        console.log("indicefirstzero " + indicefirstzero) */

        let firstzeroimpact = countzeros - indicefirstzero - 1
        let lastoneimpact = countones - (n-1-indicelastone) - 1

        //console.log("firstzeroimpact " + firstzeroimpact)
        //console.log("lastoneimpact " + lastoneimpact)

        let maximpact = Math.max(firstzeroimpact,lastoneimpact)
        if(maximpact<0)
            maximpact=0
        /*console.log("maximpact " + maximpact)
        console.log("score " + score)
        console.log("score + maximpact " + (score+ maximpact))*/
        console.log(score+ maximpact)
    }
}

const readline = require('readline')

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

function solve(n, arr) {
    let a = 0, b = 0, c = cal(n, arr)
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 0) {
            const temp = arr.slice()
            temp[i] = 1
            a = cal(n, temp)
            break
        }
    }
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i] === 1) {
            const temp = arr.slice()
            temp[i] = 0
            b = cal(n, temp)
            break
        }
    }
    return Math.max(a, b, c)
}
function cal(n, arr) {
    let zero = 0
    let r = 0
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i]) {
            r += zero
        } else {
            zero++
        }
    }
    return r
}

let buf='';

process.stdin.on('readable', function(){
    let chunk=process.stdin.read();
    if(chunk) buf+=chunk.toString();
})

function calc(a) {
    let b=new Array(a.length);
    let sum=0;
    for(let i=0;i<a.length;i++)
    {
        if(a[i]===0)
        {
            b[i]=1;
        }
        else
        {
            b[i]=0;
        }
    }
    for(let i=a.length-2;i>=0;i--) b[i]+=b[i+1];
    // console.log(b);
    for(let i=0;i<a.length;i++)
    {
        if(a[i]===1)
        {
            sum+=b[i];
        }
    }
    return sum;
}

process.stdin.on('end', function(){
    const {EOL}=require('os');
    let line=buf.split(EOL);
    let t=parseInt(line[0]);
    for(let _=1;_<=t;_++)
    {
        let n=parseInt(line[2*_-1]);
        let a=line[2*_].split(' ').map(x=>{return parseInt(x)});
        // console.log(a);
        let ans=calc(a);
        for(let i=0;i<a.length;i++)
        {
            if(a[i]===0)
            {
                a[i]=1;
                ans=Math.max(ans,calc(a));
                a[i]=0;
                break;
            }
        }
        for(let i=a.length-1;i>=0;i--)
        {
            if(a[i]===1)
            {
                a[i]=0;
                ans=Math.max(ans,calc(a));
                a[i]=1;
                break;
            }
        }
        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 main() {
    let T = parseInt(readline());
    while (T--) {
        let n = parseInt(readline());
        let ary = readline().trim().split(' ').map(s => parseInt(s));
        let t0 = ary.filter(x => x == 0).length;
        let cnt = [0, 0];
        let tot = 0;
        let mx0 = 0, mx1 = 0;
        for(let x of ary) {
            let y = t0 - cnt[0];
            if (x == 0) {
                tot += cnt[1];
                mx1 = Math.max(mx1, y - 1 - cnt[1]);
            } else {
                mx0 = Math.max(mx0, cnt[1] - y);
            }
            cnt[x]++;
        }
        // console.log(tot, mx0, mx1, cnt);
        console.log(tot + Math.max(mx0, mx1));
    }
}

    const fs = require("fs");
    const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
    let currentline = 0;
    function readline(){
          return input[currentline++];
    }
    function alph() {
      var f = 'abcdefghijklmnopqrstuvwxyz';
      return f;
    }
    function Alph() {
      var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      return f;
    }
    function max(x,y) {
      return x >=y ? x : y;
    }
    function min(x,y) {
      return x <=y ? x : y;
    }
    function abs(x) {
      return x < 0 ? x*(-1) : x;
    }
    var T = readline();
    var inf = 1000000000000;
    for(var tc=1;tc<=T;tc++) {
    	var n = readline();
    	var a = readline().split(" ").map(w => parseInt(w));
    	var pref1 = [];
    	var suf0 = [];
    	var ans1 = [];
    	var ans0 = [];
    	for(var i=0;i<n;i++) {
    		pref1[i] = (pref1[i-1]||0) + a[i];
    		if(a[i]==0) ans1[i] = (ans1[i-1]||0) + pref1[i];
    		else ans1[i] = (ans1[i-1]||0);
    	}
    	for(var i=n-1;i>=0;i--) {
    		suf0[i] = (suf0[i+1]||0) + (a[i]==0?1:0);
    		if(a[i]==1) ans0[i] = (ans0[i+1]||0) + suf0[i];
    		else ans0[i] = (ans0[i+1]||0)
    	}
    	var ans = max(ans0[0], ans1[n-1]);
    	ans = max(0, ans);
    	for(var i=0;i<n;i++) {
    		if(a[i]==0) {
    			ans = max(ans, ((ans1[i-1]||0) + (ans0[i+1]||0) + (suf0[i+1]||0)))
    		} else {
    			ans = max(ans, ((ans1[i-1]||0) + (ans0[i+1]||0) + (pref1[i-1]||0)));
    		}
    	}
    	console.log(ans);
    }

const fs = require("fs");
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
var T = readline();
var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
	var n = readline()-0;
	var a = readline().split(" ").map(w => parseInt(w));
	var pref1 = [];
	var suf0 = [];
	var ans1 = [];
	var ans0 = [];
	for(var i=0;i<n;i++) {
		pref1[i] = (pref1[i-1]||0) + a[i];
		if(!a[i]) ans1[i] = (ans1[i-1]||0) + pref1[i];
		else ans1[i] = (ans1[i-1]||0);
	}
	for(var i=n-1;i>=0;i--) {
		suf0[i] = (suf0[i+1]||0) + (a[i]===0?1:0);
		if(a[i]) ans0[i] = (ans0[i+1]||0) + suf0[i];
		else ans0[i] = (ans0[i+1]||0)
	}
	var ans = max(ans0[0], ans1[n-1]);
	ans = max(0, ans);
	for(var i=0;i<n;i++) {
		if(!a[i]) {
			ans = max(ans, (ans1[i-1]||0) + (ans0[i+1]||0) + (suf0[i+1]||0))
		} else {
			ans = max(ans, (ans1[i-1]||0) + (ans0[i+1]||0) + (pref1[i-1]||0));
		}
	}
	console.log(ans);
}

const fs = require("fs");
const input = fs.readFileSync(0, 'utf8').trim().split('\r\n');
let currentline = 0;
function readline(){
      return input[currentline++];
}
function alph() {
  var f = 'abcdefghijklmnopqrstuvwxyz';
  return f;
}
function Alph() {
  var f = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  return f;
}
function max(x,y) {
  return x >=y ? x : y;
}
function min(x,y) {
  return x <=y ? x : y;
}
function abs(x) {
  return x < 0 ? x*(-1) : x;
}
var T = readline();
var inf = 1000000000000;
for(var tc=1;tc<=T;tc++) {
	var n = readline()-0;
	var a = readline().split(" ").map(w => parseInt(w));
	var pref1 = [];
	var suf0 = [];
	var ans1 = [];
	var ans0 = [];
	for(var i=0;i<n;i++) {
		pref1[i] = (pref1[i-1]||0) + a[i];
		if(!a[i]) ans1[i] = (ans1[i-1]||0) + pref1[i];
		else ans1[i] = (ans1[i-1]||0);
	}
	for(var i=n-1;i>=0;i--) {
		suf0[i] = (suf0[i+1]||0) + (a[i]===0?1:0);
		if(a[i]) ans0[i] = (ans0[i+1]||0) + suf0[i];
		else ans0[i] = (ans0[i+1]||0)
	}
	var ans = ans1[n-1];
	for(var i=0;i<n;i++) {
		if(!a[i]) {
			ans = max(ans, (ans1[i-1]||0) + (ans0[i+1]||0) + (suf0[i+1]||0))
		} else {
			ans = max(ans, (ans1[i-1]||0) + (ans0[i+1]||0) + (pref1[i-1]||0));
		}
	}
	console.log(ans);
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var alpha = "abcdefghijklmnopqrstuvwxyz";
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var L = list.indexOf(1);
		var R = list.lastIndexOf(0);
		if(L == -1 || R == -1){
			var U = Math.floor(N / 2);
			var V = Math.ceil(N / 2);
			myout(U * V);
			continue;
		}
		for(var i = 0; i < L; i++){
			list[i] = 1;
		}
		for(var i = R; i < N; i++){
			list[i] = 0;
		}

		var sum = new Array(N + 1).fill(0);
		for(var i = N - 1; i >= 0; i--){
			if(list[i] == 0){
				sum[i]++;
			}
			sum[i] += sum[i + 1];
		}
		//myerr({list,sum});
		var output = 0;
		for(var i = 0; i < N; i++){
			if(list[i] == 1){
				output += sum[i];
			}
		}
		myout(output);
	}
}

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = nextLong();
		}else if(code == 'double'){
			ret[i] = nextDouble();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');} function nextDoubleArray(size){return nextArray(size, 'double');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());} function nextDouble(){return parseFloat(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	var alpha = "abcdefghijklmnopqrstuvwxyz";
	while(hasNext()){
		var N = nextInt();
		var list = nextIntArray(N);
		var L = list.indexOf(1);
		if(L == -1){
			list[0] = 1;
		}else{
			for(var i = 0; i < L; i++){
				list[i] = 1;
			}
		}
		var R = list.lastIndexOf(0);
		if(R != -1){
			for(var i = R; i < N; i++){
				list[i] = 0;
			}
		}else{
			list[N - 1] = 0;
		}

		var sum = new Array(N + 1).fill(0);
		for(var i = N - 1; i >= 0; i--){
			if(list[i] == 0){
				sum[i]++;
			}
			sum[i] += sum[i + 1];
		}
		//myerr({list,sum});
		var output = 0;
		for(var i = 0; i < N; i++){
			if(list[i] == 1){
				output += sum[i];
			}
		}
		myout(output);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

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

function gcd(a,b )
{
    if (!b)
        return a

    return gcd( b , a%b )
}

function main() {

    let t = parseInt(readLine());

    //let mod = 10**9+7
    loopwhile:
    while(t--)
    {
        let n = parseInt(readLine());

        let arr = readLine().trim().split(" ").map(x=>parseInt(x));

        let countzeros=0
        let countones=0
        let indicefirstzero=-1
        let indicelastone=-1
        let score = 0
        for(let i =0; i<n ;++i)
        {
            if((arr[i]==0)&&(indicefirstzero==-1))
                indicefirstzero=i

            if(arr[i]==1)
                indicelastone=i

            if(arr[i]==0)
                score +=  countones

            countzeros += (arr[i]==0)
            countones += arr[i]&1

        }
        /*console.log("countzeros " + countzeros)
        console.log("countones " + countones)
        console.log("indicelastone " + indicelastone)
        console.log("indicefirstzero " + indicefirstzero) */

        let firstzeroimpact = countzeros - indicefirstzero - 1
        let lastoneimpact = countones - (n-1-indicelastone) - 1

        /*console.log("firstzeroimpact " + firstzeroimpact)
        console.log("lastoneimpact " + lastoneimpact)*/

        let maximpact = Math.max(firstzeroimpact,lastoneimpact)
        /*console.log("maximpact " + maximpact)
        console.log("score " + score)
        console.log("score + maximpact " + (score+ maximpact))*/
        console.log(score+ maximpact)
    }
}

const readline = require('readline')

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

function solve(n, arr) {
    let a = 0, b = 0, c = cal(n, arr)
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 0) {
            const temp = arr.slice()
            temp[i] = 1
            a = cal(n, temp)
            break
        }
    }
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i] === 1) {
            const temp = arr.slice()
            temp[i] = 0
            b = cal(n, temp)
            break
        }
    }
    return Math.max(a, b)
}
function cal(n, arr) {
    let zero = 0
    let r = 0
    for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i]) {
            r += zero
        } else {
            zero++
        }
    }
    return r
}


You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the rectangle are all cells (i, j) such that x ≤ i ≤ y, z ≤ j ≤ t.

The first line contains integer a (0 ≤ a ≤ 109), the second line contains a string of decimal integers s (1 ≤ |s| ≤ 4000).

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

print(function(a, s) {
	const L = 81 * 4000 + 3;

	var i, j, ans = 0,
		l = s.length,
		p = new Int32Array(l),
		q = new Int32Array(L),
		sum = 0;

	for (i = 0; i < l; i++)
		p[i] = (sum += s[i]);

	p[-1] = 0;

	for (i = -1; i < l; i++)
		for (j = i + 1; j < l; j++)
			q[p[j] - p[i]]++;

	for (i = 0; i < L; i++)
		if (a % i === 0 && a / i < L)
			ans += q[i] * q[a / i];

	if (a === 0) {
		ans += ans + q[0]*q[0];
	}

	return ans;

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

print(function(a, s) {

	const L = 40000;

	var i, j, sum, ans = 0,
		l = s.length,
		q = new Int32Array(L);

	for (i = 0; i < l; i++)
		for (j = i, sum = 0; j < l; j++)
			q[sum += s[j]]++;

	for (i = 1; i < L; i++)
		if (a % i === 0 && a / i < L)
			ans += q[i] * q[a / i];

	if (a === 0)
		ans += ans + q[0] * q[0];

	return ans;

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

print(function(a, s) {

	const L = 40000;

	var i, j, ans = 0,
		l = s.length,
		p = new Int32Array(L),
		q = new Int32Array(L);

	for (i = 0; i < l; i++)
		p[i + 1] = p[i] + s[i];

	for (i = 0; i <= l; i++)
		for (j = 0; j < i; j++)
			q[p[i] - p[j]]++;

	for (i = 1; i < L; i++)
		if (a % i === 0 && a / i < L)
			ans += q[i] * q[a / i];

	if (a === 0)
		ans += ans + q[0] * q[0];

	return ans;

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

print(function(a, s) {

	const L = 81 * 4000 + 3;

	var i, j, ans = 0,
		l = s.length,
		p = new Int32Array(l),
		q = new Int32Array(L),
		sum = 0;

	for (i = 0; i < l; i++)
		p[i] = (sum += s[i]);

	p[-1] = 0;

	for (i = -1; i < l; i++)
		for (j = i + 1; j < l; j++)
			q[p[j] - p[i]]++;

	for (i = 1; i < L; i++)
		if (a % i === 0 && a / i < L)
			ans += q[i] * q[a / i];

	if (a === 0)
		ans += ans + q[0] * q[0];

	return ans;

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

print(function(a, s) {
	var i, l = s.length,
		p = new Int32Array(l),
		sum = 0;

	for (i = 0; i < l; i++)
		p[i] = (sum += s[i]);

	p[-1] = 0;

	var q = new Int32Array(1e6);

	for (i = -1; i < l; i++)
		for (j = i + 1; j < l; j++)
			q[p[j] - p[i]]++;

	var ans = 0;
	if (a === 0) {
		ans += q[0] * q[0];
		for (i = 1; i < 1e6; i++) {
			if (q[i] > 0)
				ans += q[i] * q[0] * 2;
		}
		return ans;
	}

	for (i = 0; i < 1e6; i++)
		if (q[i] > 0 && a % i === 0 && a / i < 1e6)
			ans += q[i] * q[a / i];

	return ans;

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

print(function(a, s) {
	var i, l = s.length,
		p = new Int32Array(l),
		sum = 0;

	for (i = 0; i < l; i++) {
		p[i] = (sum += s[i]);
	}
	p[-1] = 0;

	var q = new Int32Array(1e6);

	for (i = -1; i < l; i++) {
		for (j = i + 1; j < l; j++) {
			q[p[j] - p[i]]++;
		}
	}

	var ans = 0;
	for (i = 0; i < 1e6; i++) {
		if (q[i] > 0 && a % i === 0 && a / i < 1e6) {
			ans += q[i] * q[a / i];
		}
	}

	return ans;

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

print(function(a, s) {
	var i, l = s.length,
		p = new Int32Array(l),
		sum = 0;

	for (i = 0; i < l; i++)
		p[i] = (sum += s[i]);

	p[-1] = 0;

	var q = new Int32Array(1e6);

	for (i = -1; i < l; i++)
		for (j = i + 1; j < l; j++)
			q[p[j] - p[i]]++;

	var r=[];
	for(i=0;i<1e6;i++)
		if(q[i]>0)
			r.push(i);

	var ans=0;
	for(i=0;i<r.length;i++)
		for(j=i;j<r.length;j++)
			if(r[i]*r[j]===a)
				ans+=q[r[i]]*q[r[j]];

	return ans;

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

print(function(a, s) {
	const L = 81 * 4000 + 3;

	var i, j, ans = 0,
		l = s.length,
		p = new Int32Array(l),
		q = new Int32Array(L),
		sum = 0;

	for (i = 0; i < l; i++)
		p[i] = (sum += s[i]);

	p[-1] = 0;

	for (i = -1; i < l; i++)
		for (j = i + 1; j < l; j++)
			q[p[j] - p[i]]++;

	for (i = 0; i < L; i++)
		if (a % i === 0 && a / i < L)
			ans += q[i] * q[a / i];

	return ans;

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

print(function(a, s) {

	const L = 40000;

	var i, j, sum, ans = 0,
		l = s.length,
		q = new Int32Array(L);

	for (i = 0; i < l; i++)
		for (j = i, sum = 0; j < l; j++)
			q[sum += s[i]]++;

	for (i = 1; i < L; i++)
		if (a % i === 0 && a / i < L)
			ans += q[i] * q[a / i];

	if (a === 0)
		ans += ans + q[0] * q[0];

	return ans;

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

print(function(a, s) {
	const L = 81 * 4000 + 3;

	var i, j, ans = 0,
		l = s.length,
		p = new Int32Array(l),
		q = new Int32Array(L),
		sum = 0;

	for (i = 0; i < l; i++)
		p[i] = (sum += s[i]);

	p[-1] = 0;

	for (i = -1; i < l; i++)
		for (j = i + 1; j < l; j++)
			q[p[j] - p[i]]++;

	for (i = 0; i < L; i++)
		if (a % i === 0 && a / i < L)
			ans += q[i] * q[a / i];

	if (a === 0) {
		ans += ans + q[0];
	}

	return ans;

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


You are given a sequence of positive integers a1, a2, ..., an. While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer x + 1 on their place. This way the number of elements in the sequence is decreased by 1 on each step. You stop performing the operation when there is no pair of equal consecutive elements.For example, if the initial sequence is [5, 2, 1, 1, 2, 2], then after the first operation you get [5, 2, 2, 2, 2], after the second — [5, 3, 2, 2], after the third — [5, 3, 3], and finally after the fourth you get [5, 4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.Determine the final sequence after you stop performing the operation.

The first line contains a single integer n (2 ≤ n ≤ 2·105) — the number of elements in the sequence. The second line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print a single integer k — the number of elements in the sequence after you stop performing the operation.  In the second line print k integers — the sequence after you stop performing the operation.

NoteThe first example is described in the statements.In the second example the initial sequence is [1000000000, 1000000000, 1000000000, 1000000000]. After the first operation the sequence is equal to [1000000001, 1000000000, 1000000000]. After the second operation the sequence is [1000000001, 1000000001]. After the third operation the sequence is [1000000002].In the third example there are no two equal consecutive elements initially, so the sequence does not change.

var n = readline();
var a = readline().split(" ");
for(var i = 0; i < n; i = i + 1){
    a[i] = parseInt(a[i]);
}
var stack = [];

for(var i = 0; i < n; i = i + 1){
	stack.push(a[i]);
	//print(stack)
	while(stack.length >= 2 && stack[stack.length - 1] === stack[stack.length - 2]){
		var x = stack[stack.length - 1];
		//print(x)
		stack.pop();
		stack.pop();
		stack.push(x + 1);
	}
}
print(stack.length)
for(var i = 0; i < stack.length; i = i + 1){
	print(stack[i]);
}

var arr = readline().split(" ").map(v => +v.trim());
var n = arr[0];
var l = readline().split(" ").map(v => +v.trim());

que = []
que.push(l[0]);
for (i=1; i<n; i++)
{
    ok = 1;
    ne = l[i];
    while (ok == 1)
    {

        ok = 0;
        if(que.length > 0)
        {
            last = que.pop();
            if(last == ne)
            {
                ne = last + 1;
                ok = 1;
            }
            else
            {
                que.push(last);
            }
        }
    }
    que.push(ne);
}
print(que.length);
s = ""
for(i=0; i<que.length; i++)
{
     s = s + que[i] + " ";
}
print(s)

var n = readline();
var arr = readline().split(" ").map(v => +v.trim());
var a = [];
var k = 0;
for (i = 0; i < n; i++) {
    if (k < a.length) {
        a[k] = arr[i];
        ++k;
    } else {
        a.push(arr[i]);
        ++k;
    }
    while (k > 1) {
        if (a[k - 1] == a[k - 2]) {
            ++a[k - 2];
            --k;
        } else {
            break;
        }
    }
}
print(k)
for (i = 0; i < k; ++i) {
    print(a[i])
}

n = Number(readline())
var a = readline().split(' ').map(function(x){return Number(x)});
var b = []
k = -1;
for (i = 0; i < n; i++) {
    k += 1
    b[k] = a[i];
    while (k >= 1 && b[k] == b[k - 1]) {
        k -= 1
        b[k] = b[k + 1] + 1
    }
}
s = ""
for (i = 0; i <= k; i++) {
    s += b[i] + ' '
}
print(k + 1)
print(s)

readline()
var list = readline().split(' ').map(function(string) {
    return {
        value: Number(string),
        previous: null,
        next: null
    }
})

for (var i = 0; i < list.length; ++i) {
    if (i > 0) {
        list[i].previous = list[i - 1]
    }
    if (i < list.length - 1) {
        list[i].next = list[i + 1]
    }
}

function d(x) {
    arr = []
    do {
        arr.push(x.value)
        x = x.next
    } while(x !== null)
    print(arr.length)
    print(arr.join(' '))
}

var node = list[0]
var didGoIn;
while (node.next !== null) {
    // d(node)
    didGoIn = false
    if (node.value === node.next.value) {
        node.value += 1
        node.next = node.next.next
        if (node.next !== null) {
            node.next.previous = node
        }
        if (node.previous !== null) {
            node = node.previous
        }
        didGoIn = true
    }
    if (!didGoIn && node.next !== null)  {
        node = node.next
    }
}

while(node.previous !== null) {
    node = node.previous
}

d(node)

stack = []
var n = +readline()
var a = readline().split(' ').map(function(v){return +v;});

for (var i = 0; i < n; ++i) {
   stack.push(a[i])
   while (stack.length >= 2) {
      var sz = stack.length
      if (stack[sz-1] == stack[sz-2]) {
         stack.pop()
         stack.push(stack.pop() + 1)
      } else {
         break
      }
   }
}
print(stack.length)
print(stack.join(" "))

var n = readline();
var a = readline().split(" ");
for(var i = 0; i < n; i = i + 1){
    a[i] = parseInt(a[i]);
}
var stack = [];

for(var i = 0; i < n; i = i + 1){
	stack.push(a[i]);
	//print(stack)
	while(stack.length >= 2 && stack[stack.length - 1] === stack[stack.length - 2]){
		var x = stack[stack.length - 1];
		//print(x)
		stack.pop();
		stack.pop();
		stack.push(x + 1);
	}
}

for(var i = 0; i < stack.length; i = i + 1){
	print(stack[i]);
}

var n = readline();
var arr = readline().split(" ").map(v => +v.trim());
var a = [];
var k = 0;
for (i = 0; i < n; i++) {
    if (k < a.length) {
        a[k] = arr[i];
        ++k;
    } else {
        a.push(arr[i]);
        ++k;
    }
    while (k > 1) {
        if (a[k - 1] == a[k - 2]) {
            ++a[k - 2];
            --k;
        } else {
            break;
        }
    }
}
for (i = 0; i < k; ++i) {
    print(a[i])
}

readline()
var list = readline().split(' ').map(function(string) {
    return {
        value: Number(string),
        previous: null,
        next: null
    }
})

for (var i = 0; i < list.length; ++i) {
    if (i > 0) {
        list[i].previous = list[i - 1]
    }
    if (i < list.length - 1) {
        list[i].next = list[i + 1]
    }
}

function d(x) {
    arr = []
    do {
        arr.push(x.value)
        x = x.next
    } while(x !== null)
    print(arr.length)
    print(arr.join(' '))
}

var node = list[0]
var didGoBack;
while (node.next !== null) {
    // d(node)
    didGoBack = false
    if (node.value === node.next.value) {
        node.value += 1
        node.next = node.next.next
        if (node.next !== null) {
            node.next.previous = node
        }
        if (node.previous !== null) {
            node = node.previous
            didGoBack = true
        }
    }
    if (!didGoBack && node.next !== null)  {
        node = node.next
    }
}

while(node.previous !== null) {
    node = node.previous
}

d(node)


There is a street with $$$n$$$ houses in a line, numbered from $$$1$$$ to $$$n$$$. The house $$$i$$$ is initially painted in color $$$c_i$$$. The street is considered beautiful if all houses are painted in the same color. Tom, the painter, is in charge of making the street beautiful. Tom's painting capacity is defined by an integer, let's call it $$$k$$$.On one day, Tom can do the following repainting process that consists of two steps:   He chooses two integers $$$l$$$ and $$$r$$$ such that $$$ 1 \le l \le r \le n $$$ and $$$ r - l + 1 = k $$$.  For each house $$$i$$$ such that $$$l \le i \le r$$$, he can either repaint it with any color he wants, or ignore it and let it keep its current color. Note that in the same day Tom can use different colors to repaint different houses.Tom wants to know the minimum number of days needed to repaint the street so that it becomes beautiful.

The first line of input contains a single integer $$$t$$$ ($$$ 1 \le t \le 10^4$$$), the number of test cases. Description of test cases follows. In the first line of a test case description there are two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$). The second line contains $$$n$$$ space-separated integers. The $$$i$$$-th of these integers represents $$$c_i$$$ ($$$1 \le c_i \le 100$$$), the color which house $$$i$$$ is initially painted in. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Print $$$t$$$ lines, each with one integer: the minimum number of days Tom needs to make the street beautiful for each test case.

NoteIn the first test case Tom should paint houses 1 and 2 in the first day in color 2, houses 5 and 6 in the second day in color 2, and the last house in color 2 on the third day.In the second test case Tom can, for example, spend 6 days to paint houses 1, 2, 4, 5, 6, 7 in color 3.In the third test case Tom can paint the first house in the first day and houses 6, 7, and 8 in the second day in color 3.

const solve = (n, k, street) => {
    let map = getRecord2(street);
    let res = Number.MAX_VALUE;
    for (const ke of map.keys()) {
        let cnt = 0;
        for (let i = 0; i < n;) {
            if (street[i] != ke) {
                cnt++;
                i += k;
            } else {
                i++;
            }
        }
        res = Math.min(res, cnt);
    }
    console.log(res);
};

const getRecord2 = (arr) => {
    let map = new Map();
    for (const i of arr) {
        map.set(i, (map.get(i) + 1) || 1);
    }
    return map;
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = Number(input[0][0]);
        let i = 1;
        while (t > 0) {
            solve(input[2 * i - 1][0], input[2 * i - 1][1], input[2 * i]);
            t--;
            i++;
        }
    });
};

main()

const solve = (n, k, street) => {
    let map = sortMapByKey(getRecord2(street));
    let maxFreq = map.values().next().value;
    let res = Number.MAX_VALUE;
    for (const ke of map.keys()) {
        let occ = map.get(ke);
        if (occ != maxFreq) break;
        let cnt = 0;
        for (let i = 0; i < n;) {
            if (street[i] != ke) {
                cnt++;
                i += k;
            } else {
                i++;
            }
        }
        res = Math.min(res, cnt);
    }
    console.log(res);
};

const getRecord2 = (arr) => {
    let map = new Map();
    for (const i of arr) {
        map.set(i, (map.get(i) + 1) || 1);
    }
    return map;
};

const sortMapByKey = (map) => {
    return new Map([...map].sort((a, b) => b[0] - a[0]));
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" ").map(x => Number(x)));
    });
    rl.on('close', () => {
        let t = Number(input[0][0]);
        let i = 1;
        while (t > 0) {
            solve(input[2 * i - 1][0], input[2 * i - 1][1], input[2 * i]);
            t--;
            i++;
        }
    });
};

main()


You are given a digital clock with $$$n$$$ digits. Each digit shows an integer from $$$0$$$ to $$$9$$$, so the whole clock shows an integer from $$$0$$$ to $$$10^n-1$$$. The clock will show leading zeroes if the number is smaller than $$$10^{n-1}$$$.You want the clock to show $$$0$$$ with as few operations as possible. In an operation, you can do one of the following:   decrease the number on the clock by $$$1$$$, or  swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $$$0$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — number of digits on the clock. The second line of each test case contains a string of $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_1, s_2, \ldots, s_n \le 9$$$) — the number on the clock. Note: If the number is smaller than $$$10^{n-1}$$$ the clock will show leading zeroes.

For each test case, print one integer: the minimum number of operations needed to make the clock show $$$0$$$.

NoteIn the first example, it's optimal to just decrease the number $$$7$$$ times.In the second example, we can first swap the first and last position and then decrease the number by $$$1$$$.In the third example, the clock already shows $$$0$$$, so we don't have to perform any operations.

function main() {
     var no_of_inputs = readline()
     for(var i=0;i<no_of_inputs;i++) {
          var length = readline()
          var time = readline()
          var count = 0
          for(var j=0;j<time.length;j++) {
               if(j == time.length-1) {
                    count += parseInt(time[j])
               } else if(time[j] != 0){
                    count += 1+parseInt(time[j])
                     }
               }
          print(count)
          }
}
main()

const readline = require('readline')
function solve(s1)
{
    n = s1.length;
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0'&&(i!=n-1))
        {
            res += 1;
        }

    }
    return res;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('')
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

let stop = '';
process.stdin.on('data', c => stop += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = stop.split(EOL);
	var t = lines[0];
	var n = 0;
	for(i = 1; i <= t * 2; i++){
        if(i % 2 == 1){
            n = lines[i];
        }else{
            var s = lines[i].split('').map(Number);
            var ans = s[n - 1];
            for(j = 0; j < n - 1; j++){
                if(s[j] !== 0){
                    ans += (s[j]) + 1;
                }
            }
            console.log(ans);
        }
	}
});

//https://codeforces.com/problemset/problem/1573/A?locale=en
process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';

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

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

    main(inputString);
});

function log(message) {
    if (process.env.NODE_ENV === "debug") {
        console.log(message);
    }
}

function calculateStepsNeededFor0(digits) {
    const digitProcessor = (accumulator, currentValue, currentIndex) => {
        const costOfMoving = 1;
        const isLastDigit = currentIndex === digits.length-1;

        if(isLastDigit){
            return accumulator + currentValue;
        }else{
            if(currentValue === 0){
                return accumulator
            }else{
                return accumulator + currentValue + costOfMoving;
            }
        }
    }

    const allNumbersSummarised = String(digits)
        .split("")
        .map(x => Number(x))
        .reduce(digitProcessor, 0);

    return allNumbersSummarised;
}

function main(fileContents) {//input lines as an array
    // console.log(fileContents);
    const header = fileContents.splice(0, 1);
    const tasksWithoutLength = fileContents.filter((elem, id) => id % 2 !== 0)

    const clockTransformationSteps = tasksWithoutLength
        .map(calculateStepsNeededFor0);

    //PrintOutput
    clockTransformationSteps.forEach((x) => console.log(x))
}

"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.split("\n");
  main();
});
function readline() {
  return inputString[currentLine++];
}

function main() {
  var t = +(readline());
  while (t--) {
    solution();
  }
}

function solution() {
  const n = +(readline());
  const str = readline();

  let ans = 0;
  for (let i = 0; i < n-1; i++) {
    let s = (str[i] === '0') ? 0 : +str[i]+1;
    ans+=s;
  }
  ans += +str[n-1];
  console.log(ans);
}

function isPrime(num) {
  if (num === 2) return true;
    if (num === 1 || num%2 === 0 ) return false;

    let root = Math.floor(Math.sqrt(num));
    root += (root%2)-1;
    while (root > 1) {
      if (num%root === 0)
        return false;
      root -= 2;
    }
    return true;
}

let data = '';
process.stdin.on('data', c => data += c);

function* nextLine() {
	let lines = data.trim().split(/\n/g);
	for(let l of lines){
		yield l.trim();
	}
}

let nl = nextLine();

nl.elem = function(funParse) {
		return funParse(this.next().value);
	};

nl.array = function(funParse) {
		return this.next().value.split(/\s/g).map(funParse||(x => x));
	};

nl.num = function() {
		return nl.elem(Number);
	};

nl.nums = function() {
		return nl.array(Number);
	};

nl.line = function() {
		return this.next().value;
	};

const sol = () => {
	//your code this
	let t = nl.num();
	let ans = [];
	for(let i = 0; i < t; i++){
		let n = nl.num();
		let s = nl.line();
		let r = 0;
		for(let j = n - 1; j >= 0; j--){
			let x = Number(s.charAt(j));
			if (x > 0) {
				r += x;
				if (j < n-1) {
					r++;
				}
			}
		}
		ans.push(r);
	}
	console.log(ans.join('\n'));
};

process.stdin.on('end', sol);

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else if(code == 'long'){
			ret[i] = BigInt(next());
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');} function nextLongArray(size){return nextArray(size, 'long');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);} function nextLong(){return BigInt(next());}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
	var t = nextInt();
	while(hasNext()){
		var N = nextInt();
		var s = next();
		var output = 0;
		for(var i = 0; i < N; i++){
			var v = myconv(s[i], 1);
			if(v > 0){
				if(i < N - 1){
					output += v + 1;
				}else{
					output += v;
				}
			}

		}
		myout(output);
	}
}

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', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})

function solve(str) {
    let count=0
    for(let j=0;j<str.length;j++){
        const digit=Number(str[j])
        if(j!==0){
            if(digit!==0) count=count+1
        }
        count=count+digit
    }
    return count;
}

const nextString = (function() {
  const listeners = [], strings = [], ps = process.stdin
  let last = ''
  ps.setEncoding('utf8')
  ps.on('readable', () => {
    let chunk
    while ((chunk = ps.read()) !== null) {
      chunk = (last + chunk).split(/\r\n|\r|\n/)
      last = chunk[chunk.length - 1]
      for (let i = 0; i < chunk.length - 1; ++i) {
        if (chunk[i].length > 0) {
          if (listeners.length > 0) {
            listeners.shift()(chunk[i])
          }
          else {
            strings.push(chunk[i])
          }
        }
      }
    }
  })
  const fn = resolve => {
    if (strings.length > 0) {
      resolve(strings.shift())
    }
    else {
      listeners.push(resolve)
    }
  }
  return () => new Promise(fn)
})()

async function main() {
  let t = +await nextString()
  for (let iii = 0; iii < t; ++iii) {
    let n = +await nextString()
    let mas = (await nextString()).split('').map(char => +char)
    let ans = 0
    ans += mas[mas.length - 1]
    mas[mas.length - 1] = 0
    while (true) {
      let p = 0
      while (p < mas.length && mas[p] === 0) {
        ++p
      }
      if (p === mas.length) {
        break
      }
      let temp = mas[p]
      mas[p] = mas[n - 1]
      mas[n - 1] = temp
      ans += mas[n - 1]
      mas[n - 1] = 0
      ++ans
    }
    console.log(ans)
  }
}

main()

const readline = require('readline')
function solve(s1)
{
    n = s1.length;
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0'&&(i!=n-1))
        {
            res += 1;
        }

    }
    return res;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

const readline = require('readline')
function solve(s1)
{
    n = s1.length;
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0')
        {
            res += 1;
        }

    }
    return res-1;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

const readline = require('readline')
function solve(s1)
{
    let res = 0;
    for(let i=0;i<n;i++)
    {
        res += parseInt(s1[i]);
        if(s1[i]!='0')
        {
            res += 1;
        }

    }
    return res-1;
}
var n;

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})
const lines = []
rl.on('line', (input) => {
    lines.push(input)
})
rl.on('close', () => {
    let l = 0
    let t = lines[l++]
    for (let i = 0; i < t; i++) {
        const n = lines[l++]
        const str = lines[l++].trim().split('').reverse()
        console.log(solve(str))
    }
})
// var n = readLine();
// var in1 = readLine();
// console.log(solve(in1,parseInt(n)));

let i = '';
process.stdin.on('data', c => i += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = i.split(EOL);
    var n = lines[0];
    var e = 0;
    for(var j = 1; j <= n * 2; j++){
        if(j % 2 === 0){
            var k = lines[j].split(' ').map(Number);
            k = k.sort(function(a, b){return a - b});
            var a = [];
            for(var l = 1; l <= k.length; l++){
                if(k[l] != k[l - 1]){
                    a.push(k[l - 1]);
                }
            }
            if(a.length == 1){
                console.log(e);
            }else{
                console.log(1);
            }
        }else{
            e = lines[j];
        }
    }
});

///https://codeforces.com/problemset/problem/1452/A

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

let inputString = '';

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

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

    main(inputString);
});

function main(fileContents) {//input lines as an array
    const amoutOfInputsForTheProgram = fileContents.splice(0,1);
    const listOfEndpointsForRobot = [...fileContents];

    listOfEndpointsForRobot
        .map((endpoints)=>endpoints.split(" "))
        .map((endpoints)=>{
           const diffBetweetVertAndHorizontal = Math.abs(parseInt(endpoints[0])-parseInt(endpoints[1]));
           return parseInt(endpoints[0])+parseInt(endpoints[1])
               +(diffBetweetVertAndHorizontal > 0 ? (diffBetweetVertAndHorizontal-1) : 0)
        })
        .forEach(x=>console.log(x));

}