var t = parseInt(readline());

  while (t--) {
    var input1 = readline().split(" ");
    var input2 = readline().split(" ");

    var x1 = parseInt(input1[0]);
    var p1 = parseInt(input1[1]);

    var x2 = parseInt(input2[0]);
    var p2 = parseInt(input2[1]);

    var m = Math.min(p1, p2);
    p1 -= m;
    p2 -= m;
    if (p1 >= 7) {
      print(">");
    } else if (p2 >= 7) {
      print("<");
    } else {
      for (var j = 0; j < p1; j++) {
        x1 *= 10;
      }
      for (var j = 0; j < p2; j++) {
        x2 *= 10;
      }
      if (x1 > x2) {
        print(">");
      } else if (x1 < x2) {
        print("<");
      } else {
        print("=");
      }
    }
  }

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

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

function main () {
	let T = rn();
	while (T--) {
		let [x1, p1] = rna();
		let [x2, p2] = rna();

		const mn = Math.min(p1, p2);
		p1 -= mn;
		p2 -= mn;

		while (x1 <= 1e6 && p1) { x1 *= 10; p1--; }
		while (x2 <= 1e6 && p2) { x2 *= 10; p2--; }
		let ans = x1 - x2;

		if (ans <  0) console.log('<');
		if (ans == 0) console.log('=');
		if (ans >  0) console.log('>');
	}
}

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

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

function main () {
	let T = rn();
	while (T--) {
		let [x1, p1] = rna();
		let [x2, p2] = rna();

		while (x1 <= 1e6-1 && p1) { x1 *= 10; p1--; }
		while (x2 <= 1e6-1 && p2) { x2 *= 10; p2--; }
		if (p1 > p2) x1 *= 10;
		if (p2 > p1) x2 *= 10;
		let ans = x1 - x2;

		if (ans <  0) console.log('<');
		if (ans == 0) console.log('=');
		if (ans >  0) console.log('>');
	}
}

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

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

function main () {
	let T = rn();
	while (T--) {
		let [x1, p1] = rna();
		let [x2, p2] = rna();

		let ans;
		if (String(x1).length + p1 < String(x2).length + p2)
			ans = -1;
		else if (String(x1).length + p1 > String(x2).length + p2)
			ans = 1;
		else {
			while (x1 <= 1e6-1) x1 *= 10;
			while (x2 <= 1e6-1) x2 *= 10;
			ans = x1 - x2;
		}

		if (ans <  0) console.log('<');
		if (ans == 0) console.log('=');
		if (ans >  0) console.log('>');
	}
}

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

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

const MX = 1e6 + 7;

function main () {
	let T = rn();
	while (T--) {
		let [x1, p1] = rna();
		let [x2, p2] = rna();

		let ans = x1 * Math.pow(10, Math.min(Math.max(p1 - p2, 0), 7)) -
	  		      x2 * Math.pow(10, Math.min(Math.max(p2 - p1, 0), 7));

		ans = ans == 0 ? '=' : (ans > 0 ? '>' : '<');
		console.log(ans);
	}
}

/**
 * https://codeforces.com/problemset/problem/1613/A
 */

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

    const input = [];
    return new Promise((resolve) => {
        readLine.on('close', () => resolve(input));
        readLine.on('line', (line) => input.push(line));
    });
}

/**
 *
 * @param {Array<number>} data
 * @param {number} testCount
 * @param {number} linesPerCase
 * @returns {Array<string>}
 */
function* splitTestCase(data, testCount, linesPerCase) {
    for (let i = 0, ii = 0; i < testCount; i++, ii = i * linesPerCase) {
        yield data.slice(ii, ii + linesPerCase);
    }
}

/**
 *
 * @param {Array<string>} arr
 * @returns {number}
 */
function len(arr) {
    return arr[0].length + Number.parseInt(arr[1]) || 0;
}

/**
 *
 * @param {number} x1
 * @param {number} x2
 * @returns {string | undefined}
 */
function compare(x1, x2) {
    if (x1 > x2) { return '>'; }
    if (x1 < x2) { return '<'; }

    return;
}

/**
 *
 * @param {Array<string>} input1
 * @param {Array<string>} input2
 */
function run(input1, input2) {
    // Early escape
    if (input1 === input2) { return '='; }

    let result = compare(len(input1), len(input2));
    if (result) { return result; }

    // Inputs have the same length, normalize length of meaningful part and compare
    const normalizedLen = Math.max(input1[0].length, input2[0].length);
    result = compare(Number.parseInt(input1[0].padEnd(normalizedLen, 0)), Number.parseInt(input2[0].padEnd(normalizedLen, 0)));
    if (result) { return result; }

    return '=';
}

nodeJSReader().then(([
    testCount,
    ...data
]
) => {
    for (const testCase of splitTestCase(data, testCount, 2)) {
        console.log(run(testCase[0].split(' '), testCase[1].split(' ')));
    }
});

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 [x1, p1] = lines[l++].trim().split(' ')
        const [x2, p2] = lines[l++].trim().split(' ')
        output[i] = solve(x1, p1, x2, p2)
    }
    console.log(output.join('\n'))
// })()
})

function solve(x1, p1, x2, p2) {
    p1 = +p1
    p2 = +p2
    if (x1.length + p1 > x2.length + p2) return '>'
    if (x1.length + p1 < x2.length + p2) return '<'

    const min = Math.min(p1, p2)
    p1 -= min
    p2 -= min
    let i = 0
    let j = 0
    while (i < p1 + x1.length && j < p2 + x2.length) {
        const a = i < x1.length ? +x1[i] : 0
        const b = j < x2.length ? +x2[j] : 0
        // console.log('sb', a, b)
        if (a < b) return '<'
        if (a > b) return '>'
        i++
        j++
    }
    return '='
}

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 main(fileContents) {//input lines as an array
    // console.log(fileContents);
    fileContents.splice(0,1);

    for(let i = 0; i< fileContents.length-1; i+=2){
        const row1 = fileContents[i].split(" ");
        const num1base = row1[0]/Math.pow(10,row1[0].length-1)
        const num1pow = row1[0].length-1+parseInt(row1[1])

        const row2 = fileContents[i+1].split(" ");
        const num2base = row2[0]/Math.pow(10,row2[0].length-1)
        const num2pow = row2[0].length-1+parseInt(row2[1])

        // console.log(num1base,num1pow , num2base, num2pow)

        if(num1pow > num2pow){
            console.log(">")
        }else if(num1pow < num2pow){
            console.log("<")
        }else{
           if(num1base > num2base){
               console.log(">")
           }else if(num1base < num2base){
               console.log("<")
           }else{
               console.log("=")
           }
        }
    }

}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    n1 = parseInt(n1);
    n2 = parseInt(n2);
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function compareCharNumbers(n1, n2) {
    n1 = String(n1);
    n2 = String(n2);
    for (var i = 0; i < n1.length; i++){
        var compareRes = compareNumbers(n1[i], n2[i]);
        if (compareRes !== '=') return compareRes;
    }

    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    var i = zeroCount;
    var res = str + '';
    while (i > 0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var digs1 = arr1[0] === '0' ? 0 : (arr1[0].length + parseInt(arr1[1]));
    var digs2 = arr2[0] === '0' ? 0 : (arr2[0].length + parseInt(arr2[1]));

    if (digs1 === digs2) {
        var p_diff = Math.abs(arr1[1] - arr2[1]);
        var n1 = addZeroesToNumber(arr1[0], arr1[1] > arr2[1] ? p_diff : 0);
        var n2 = addZeroesToNumber(arr2[0], arr2[1] > arr1[1] ? p_diff : 0);
        results.push(compareCharNumbers(n1, n2));
    } else results.push(compareNumbers(digs1, digs2));
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    n1 = parseInt(n1);
    n2 = parseInt(n2);
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function compareCharNumbers(n1, n2) {
    n1 = String(n1);
    n2 = String(n2);
    for (var i = 0; i < n1.length; i++){
        var compareRes = compareNumbers(n1[i], n2[i]);
        if (compareRes !== '=') return compareRes;
    }

    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    // if (zeroCount === 0 || zeroCount === '0') {
    //     return parseInt(str);
    // }

    var i = zeroCount;
    var res = str + '';
    while (i > 0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var digs1 = arr1[0] === '0' ? 0 : (arr1[0].length + parseInt(arr1[1]));
    var digs2 = arr2[0] === '0' ? 0 : (arr2[0].length + parseInt(arr2[1]));

    if (digs1 === digs2) {
        var p_diff = Math.abs(arr1[1] - arr2[1]);
        var n1 = addZeroesToNumber(arr1[0], arr1[1] > arr2[1] ? p_diff : 0);
        var n2 = addZeroesToNumber(arr2[0], arr2[1] > arr1[1] ? p_diff : 0);
        results.push(compareCharNumbers(n1, n2));
    } else results.push(compareNumbers(digs1, digs2));
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var t = +readline();

while(t--) {
    var d1 = readline().split(' ');
    var d2 = readline().split(' ');
    var a = d1[0], b = d2[0];
    var ans = "=";

    var len1 = d1[0].length + Number(d1[1]);
    var len2 = d2[0].length + Number(d2[1]);

    if(len1 === len2) {
        a += "0".repeat(Math.max(0, b.length - a.length));
        b += "0".repeat(Math.max(0, a.length - b.length));
        ans = +a > +b ?  ">" : +a < +b ? "<" : "=";
    } else if (len1 > len2) {
        ans = ">";
    } else {
        ans = "<";
    }

    print(ans);
}

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

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

function main () {
	let T = rn();
	while (T--) {
		let [x1, p1] = rna();
		let [x2, p2] = rna();

		while (x1 <= 1e6-1 && p1) { x1 *= 10; p1--; }
		while (x2 <= 1e6-1 && p2) { x2 *= 10; p2--; }
		let ans = x1 - x2;

		if (ans <  0) console.log('<');
		if (ans == 0) console.log('=');
		if (ans >  0) console.log('>');
	}
}

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

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

function main () {
	let T = rn();
	while (T--) {
		let [x1, p1] = rna();
		let [x2, p2] = rna();

		let ans;
		if (String(x1).length + p1 < String(x2).length + p2)
			ans = -1;
		else if (String(x1).length + p1 > String(x2).length + p2)
			ans = 1;
		else {
			while (x1 <= 1e6) x1 *= 10;
			while (x2 <= 1e6) x2 *= 10;
			ans = x1 - x2;
		}

		if (ans <  0) console.log('<');
		if (ans == 0) console.log('=');
		if (ans >  0) console.log('>');
	}
}

/**
 * https://codeforces.com/problemset/problem/1613/A
 */

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

    const input = [];
    return new Promise((resolve) => {
        readLine.on('close', () => resolve(input));
        readLine.on('line', (line) => input.push(line));
    });
}

/**
 *
 * @param {Array<number>} data
 * @param {number} testCount
 * @param {number} linesPerCase
 * @returns {Array<string>}
 */
function* splitTestCase(data, testCount, linesPerCase) {
    for (let i = 0, ii = 0; i < testCount; i++, ii = i * linesPerCase) {
        yield data.slice(ii, ii + linesPerCase);
    }
}

/**
 *
 * @param {Array<string>} arr
 * @returns {number}
 */
function len(arr) {
    return arr[0].length + Number.parseInt(arr[1]) || 0;
}

/**
 *
 * @param {number} x1
 * @param {number} x2
 * @returns {string | undefined}
 */
function compare(x1, x2) {
    console.log('>>>>', x1, x2);
    if (x1 > x2) { return '>'; }
    if (x1 < x2) { return '<'; }

    return;
}

/**
 *
 * @param {Array<string>} input1
 * @param {Array<string>} input2
 */
function run(input1, input2) {
    // Early escape
    if (input1 === input2) { return '='; }

    let result = compare(len(input1), len(input2));
    if (result) { return result; }

    // Inputs have the same length, normalize length of meaningful part and compare
    const normalizedLen = Math.max(input1[0].length, input2[0].length);
    result = compare(Number.parseInt(input1[0].padEnd(normalizedLen, 0)), Number.parseInt(input2[0].padEnd(normalizedLen, 0)));
    if (result) { return result; }

    return '=';
}

nodeJSReader().then(([
    testCount,
    ...data
]
) => {
    for (const testCase of splitTestCase(data, testCount, 2)) {
        console.log(run(testCase[0].split(' '), testCase[1].split(' ')));
    }
});

/**
 * https://codeforces.com/problemset/problem/1613/A
 */

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

    const input = [];
    return new Promise((resolve) => {
        readLine.on('close', () => resolve(input));
        readLine.on('line', (line) => input.push(line));
    });
}

/**
 *
 * @param {Array<number>} data
 * @param {number} testCount
 * @param {number} linesPerCase
 * @returns {Array<string>}
 */
function* splitTestCase(data, testCount, linesPerCase) {
    for (let i = 0, ii = 0; i < testCount; i++, ii = i * linesPerCase) {
        yield data.slice(ii, ii + linesPerCase);
    }
}

/**
 *
 * @param {Array<string>} arr
 * @returns {number}
 */
function len(arr) {
    return arr[0].length + Number.parseInt(arr[1]) || 0;
}

/**
 *
 * @param {number} x1
 * @param {number} x2
 * @returns {string | undefined}
 */
function compare(x1, x2) {
    console.log('>>>>', x1, x2);
    if (x1 > x2) { return '>'; }
    if (x1 < x2) { return '<'; }

    return;
}

/**
 *
 * @param {Array<string>} input1
 * @param {Array<string>} input2
 */
function run(input1, input2) {
    // Early escape
    if (input1 === input2) { return '='; }

    let result = compare(len(input1), len(input2));
    if (result) { return result; }

    // Inputs have the same length, normalize length of meaningful part and compare
    const normalizedLen = Math.max(input1[0].length, input2[0].length);
    result = compare(Number.parseInt(input1[0].padEnd(normalizedLen, 0)), Number.parseInt(input2[0].padEnd(normalizedLen, 0)));
    if (result) { return result; }

    return '=';
}

nodeJSReader().then(([
    testCount,
    ...data
]
) => {
    for (const testCase of splitTestCase(data, testCount, 2)) {
        console.log(testCase, run(testCase[0].split(' '), testCase[1].split(' ')));
    }
});

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    if (zeroCount === 0 || zeroCount === '0') {
        return parseInt(str);
    }
    var i = zeroCount;
    var res = str + '';
    while (i > 0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var digs1 = arr1[0] === '0' ? 0 : (arr1[0].length + parseInt(arr1[1]));
    var digs2 = arr2[0] === '0' ? 0 : (arr2[0].length + parseInt(arr2[1]));

    if (digs1 === digs2) {
        var p_diff = Math.abs(arr1[1] - arr2[1]);
        var n1 = addZeroesToNumber(arr1[0], arr1[1] > arr2[1] ? p_diff : 0);
        var n2 = addZeroesToNumber(arr2[0], arr2[1] > arr1[1] ? p_diff : 0);
        results.push(compareNumbers(n1, n2));
    } else results.push(compareNumbers(digs1, digs2));
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    var i = zeroCount;
    var res = str + '';
    while (i > 0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var digs1 = arr1[0] === '0' ? 0 : (arr1[0].length + parseInt(arr1[1]));
    var digs2 = arr2[0] === '0' ? 0 : (arr2[0].length + parseInt(arr2[1]));

    if (digs1 === digs2) {
        var p_diff = Math.abs(arr1[1] - arr2[1]);
        var n1 = addZeroesToNumber(arr1[0], arr1[1] > arr2[1] ? p_diff : 0);
        var n2 = addZeroesToNumber(arr2[0], arr2[1] > arr1[1] ? p_diff : 0);
        results.push(compareNumbers(n1, n2));
    } else results.push(compareNumbers(digs1, digs2));
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    var i = zeroCount;
    var res = str + '';
    while (i > 0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var digs1 = (arr1[0] === '0' ? 0 : arr1[0].length) + parseInt(arr1[1]);
    var digs2 = (arr2[0] === '0' ? 0 : arr2[0].length) + parseInt(arr2[1]);

    if (digs1 === digs2) {
        var p_diff = Math.abs(arr1[1] - arr2[1]);
        var n1 = addZeroesToNumber(arr1[0], arr1[1] > arr2[1] ? p_diff : 0);
        var n2 = addZeroesToNumber(arr2[0], arr2[1] > arr1[1] ? p_diff : 0);
        results.push(compareNumbers(n1, n2));
    } else results.push(compareNumbers(digs1, digs2));
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    var i = zeroCount;
    var res = str + '';
    while (i > 0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var digs1 = arr1[0].length + parseInt(arr1[1]);
    var digs2 = arr2[0].length + parseInt(arr2[1]);

    if (digs1 === digs2) {
        var p_diff = Math.abs(arr1[1] - arr2[1]);
        var n1 = addZeroesToNumber(arr1[0], arr1[1] > arr2[1] ? p_diff : 0);
        var n2 = addZeroesToNumber(arr2[0], arr2[1] > arr1[1] ? p_diff : 0);
        results.push(compareNumbers(n1, n2));
    } else results.push(compareNumbers(digs1, digs2));
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    var i = zeroCount;
    var res = str;
    while (i>0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var p_diff = Math.abs(arr1[1] - arr2[1]);

    var n1 = getNumber(arr1, arr2, p_diff);
    var n2 = getNumber(arr2, arr1, p_diff);
    results.push(compareNumbers(n1, n2))
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    var i = zeroCount;
    var res = str;
    while (i>0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().trim().split(" ");
}

function getNumber(arr1, arr2, p_diff) {
    return arr1[1] > arr2[1] ? addZeroesToNumber(arr1[0], p_diff) : parseInt(arr1[0]);
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var p_diff = Math.abs(arr1[1] - arr2[1]);

    var n1 = getNumber(arr1, arr2, p_diff);
    var n2 = getNumber(arr2, arr1, p_diff);
    print(n1, n2);
    results.push(compareNumbers(n1, n2))
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var pairsCount = parseInt(readline());

var results = [];

function compareNumbers(n1, n2) {
    if (n1 < n2) return '<';
    if (n1 > n2) return '>';
    return '=';
}

function addZeroesToNumber(str, zeroCount) {
    var i = zeroCount;
    var res = str;
    while (i>0) {
        res += '0';
        i--;
    }
    return parseInt(res);
}

function getReadLineArray() {
    return readline().toString().split(" ");
}

var i = 0;
while (i < pairsCount) {
    var arr1 = getReadLineArray();
    var arr2 = getReadLineArray();

    var p2 = Math.abs(arr1[1] - arr2[1]);

    var n1 = addZeroesToNumber(arr1[0], arr1[1] > arr2[1] ? p2 : 0);
    var n2 = addZeroesToNumber(arr2[0], arr2[1] > arr1[1] ? p2 : 0);
    results.push(compareNumbers(n1, n2))
    i++;
}

for (var j = 0; j < results.length; j++) {
    print(results[j]);
}

var t = +readline();

while(t--) {
    var description1 = readline().split(' ').map(Number);
    var description2 = readline().split(' ').map(Number);

    var firstNumber = description1[0] * (Math.pow(10, description1[1]));
    var secondNumber = description2[0] * (Math.pow(10, description2[1]));

    print(firstNumber === secondNumber ? '=' : firstNumber > secondNumber ? '>' : '<');
}


function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

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

  if(Math.max(...arr.map(item => item.length)) > 10) {
    var res = parseInt(arr.map(item => +item.slice(0, -7) / 2).reduce((prev, curr) => prev + curr));
    var lres = parseInt(arr.map(item => +item.slice(-13) / 2).reduce((prev, curr) => prev + curr));
    print(res.toString().slice(0, -3) + padStart(lres.toString().slice(-10), 10, '0'));
  } else {
    var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);
    print(res);
  }
}

var firstLine = +readline();
var i = 0;

while(i < firstLine) {
	var arr = readline().split(' ');
	var arrRes = arr.reduce((a,b) => add(a, b), "0");
    arrRes = divide(arrRes, 2).split('.')[0];
	print(arrRes[0] == "0" ? arrRes.substring(1) : arrRes);

	i++;
}

function add(str1, str2) {
    var sum = "";

    var str1Length = str1.length;
    var str2Length = str2.length;

    if(str2Length > str1Length ){
        var temp = str2;
        str2 = str1;
        str1 = temp;
    }

    var carry = 0;
    var a;
    var b;
    var temp;
    var digitSum;
    for (var i = 0; i < str1.length; i++) {
        a = parseInt(str1.charAt(str1.length - 1 - i));
        b = parseInt(str2.charAt(str2.length - 1 - i));
        b = (b) ? b : 0;
        temp = (carry + a + b).toString();
        digitSum = temp.charAt(temp.length - 1);
        carry = parseInt(temp.substr(0, temp.length - 1));
        carry = (carry) ? carry : 0;

        sum = (i === str1.length - 1) ? temp + sum : digitSum + sum;

    }

    return sum;     // return sum

}

function divide(n,d){
    var num = n + "",
        numLength = num.length,
        remainder = 0,
        answer = '',
        i = 0;

    while( i < numLength + 3){
        var digit = i < numLength ? parseInt(num[i]) : 0;

        if (i == numLength){
            answer = answer + ".";
        }

        answer = answer + Math.floor((digit + (remainder * 10))/d);
        remainder = (digit + (remainder * 10))%d;
        i++;
    }
    return answer;
}

var firstLine = +readline();
var i = 0;

while(i < firstLine) {
	var arr = readline().split(' ');
	var arrRes = arr.reduce((a,b) => add(a, b), "0");

    arrRes = divide(arrRes, 2)
	print(arrRes.split('.')[0]);

	i++;
}

function add(str1, str2) {
    var sum = "";

    var str1Length = str1.length;
    var str2Length = str2.length;

    if(str2Length > str1Length ){
        var temp = str2;
        str2 = str1;
        str1 = temp;
    }

    var carry = 0;
    var a;
    var b;
    var temp;
    var digitSum;
    for (var i = 0; i < str1.length; i++) {
        a = parseInt(str1.charAt(str1.length - 1 - i));
        b = parseInt(str2.charAt(str2.length - 1 - i));
        b = (b) ? b : 0;
        temp = (carry + a + b).toString();
        digitSum = temp.charAt(temp.length - 1);
        carry = parseInt(temp.substr(0, temp.length - 1));
        carry = (carry) ? carry : 0;

        sum = (i === str1.length - 1) ? temp + sum : digitSum + sum;

    }

    return sum;     // return sum

}

function divide(n,d){
    var num = n + "",
        numLength = num.length,
        remainder = 0,
        answer = '',
        i = 0;

    while( i < numLength + 3){
        var digit = i < numLength ? parseInt(num[i]) : 0;

        if (i == numLength){
            answer = answer + ".";
        }

        answer = answer + Math.floor((digit + (remainder * 10))/d);
        remainder = (digit + (remainder * 10))%d;
        i++;
    }
    return answer;
}

var firstLine = +readline();
var i = 0;

while(i < firstLine) {
	var arr = readline().split(' ');
	var arrSum = arr.reduce((a,b) => add(a, b), "0");

	print(Math.floor(divide(arrSum, 2)));

	i++;
}

function add(str1, str2) {
    var sum = "";
    var str1Length = str1.length;
    var str2Length = str2.length;

    if(str2Length > str1Length ){
        var temp2 = str2;
        str2 = str1;
        str1 = temp2;
    }

    var carry = 0;  // number that is carried to next decimal place, initially zero.
    var a;
    var b;
    var temp;
    var digitSum;
    for (var i = 0; i < str1.length; i++) {
        a = parseInt(str1.charAt(str1.length - 1 - i));
        b = parseInt(str2.charAt(str2.length - 1 - i));
        b = (b) ? b : 0;
        temp = (carry + a + b).toString();
        digitSum = temp.charAt(temp.length - 1);
        carry = parseInt(temp.substr(0, temp.length - 1));
        carry = (carry) ? carry : 0;

        sum = (i === str1.length - 1) ? temp + sum : digitSum + sum;
    }

    return sum;     // return sum
}

function divide(n,d){
    var num = n + "",
        numLength = num.length,
        remainder = 0,
        answer = '',
        i = 0;

    while( i < numLength + 3){
        var digit = i < numLength ? parseInt(num[i]) : 0;

        if (i == numLength){
            answer = answer + ".";
        }

        answer = answer + Math.floor((digit + (remainder * 10))/d);
        remainder = (digit + (remainder * 10))%d;
        i++;
    }
    return parseFloat(answer);
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

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

  if(Math.max(...arr.map(item => item.length)) > 10) {
    var res = parseInt(arr.map(item => +item.slice(0, -8)).reduce((prev, curr) => prev + curr) / 2);
    var lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString() + padStart(lres.toString().slice(-8), 8, '0'));
  } else {
    var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);
    print(res);
  }
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var arr = readline().split(' ');
  var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);

  if(res > Number.MAX_SAFE_INTEGER) {
    var lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString().slice(0, -10) + padStart(lres.toString().slice(-10), 10, '0'));
  } else {
    print(res);
  }
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

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

  if(Math.max(...arr.map(item => item.length)) > 10) {
    var res = parseInt(arr.map(item => +item.slice(0, -8) / 2).reduce((prev, curr) => prev + curr));
    var lres = parseInt(arr.map(item => +item.slice(-12) / 2).reduce((prev, curr) => prev + curr));
    print(res.toString().slice(0, -2) + padStart(lres.toString().slice(-10), 10, '0'));
  } else {
    var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);
    print(res);
  }
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var val = readline().split(' ').reduce((curr, prev) => curr + (+prev), 0);
  print(Math.floor(val / 2));
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var arr = readline().split(' ');
  var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);

  if(res > 10000000000) {
    var lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString().slice(0, -9) + padStart(lres.toString().slice(-9), 9, '0'));
  } else {
    print(res);
  }
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var arr = readline().split(' ');
  var res = parseInt(arr.map(item => +item.slice(0, -9)).reduce((prev, curr) => prev + curr) / 2);

  if(Math.max(...arr.map(item => item.length)) > 10) {
    var lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString().slice(0, -1) + padStart(lres.toString().slice(-9), 9, '0'));
  } else {
    print(res);
  }
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var arr = readline().split(' ');
  var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);

  if(res > Number.MAX_SAFE_INTEGER) {
    var lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString().slice(0, -9) + padStart(lres.toString().slice(-9), 9, '0'));
  } else {
    print(res);
  }
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var arr = readline().split(' ');
  var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);

  if(res > Number.MAX_SAFE_INTEGER) {
    lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString().slice(0, -10) + lres.toString().slice(-10));
  } else {
    print(res);
  }
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

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

  if(Math.max(...arr.map(item => item.length)) > 10) {
    var res = parseInt(arr.map(item => +item.slice(0, -9)).reduce((prev, curr) => prev + curr) / 2);
    var lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString() + padStart(lres.toString().slice(-9), 9, '0'));
  } else {
    var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);
    print(res);
  }
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var arr = readline().split(' ').map(item => +item).sort((a, b) => a - b);
  var sum = arr[1] + (arr[2] - arr[1] + arr[0]) / 2;

  print(Math.floor(sum));
}

function padStart(str, count, symbol) {
  for(var i = str.length; i < count; i++) {
    str = '0' + str;
  }

  return str;
}

var n = +readline();

for(var i = 0; i < n; i++) {
  var arr = readline().split(' ');
  var res = parseInt(arr.map(item => +item).reduce((prev, curr) => prev + curr) / 2);

  if(res > 1000000000) {
    var lres = parseInt(arr.map(item => +item.slice(-10)).reduce((prev, curr) => prev + curr) / 2);
    print(res.toString().slice(0, -9) + padStart(lres.toString().slice(-9), 10, '0'));
  } else {
    print(res);
  }
}


process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '', currentLine = 0;
process.stdin.on('data', inputStdin => { inputString += inputStdin; });
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => string.trim());
    main();
});
function readLine() {
    return inputString[currentLine++];
}

function main() {
    const t = parseInt(readLine(), 10);
    for(let i = 0; i < t; i++){
        const n = +readLine();
        const arr = readLine().split(' ').map(p => +p);
        const resp = myFunc(n, arr);
        console.log(resp);
    }
}

function myFunc(n, arr){

    let first;
    let aux;
    let map = [];

    function calculate(arr){
        let resp = 0;
        for(let i = 1; i < n-1; i+=2){
            aux = Math.max(arr[i-1], arr[i+1]);
            if(aux < arr[i]){
                map[i] = 0;
                continue;
            }
            map[i] = aux - arr[i] + 1;
            resp += aux - arr[i] + 1;
        }
        return resp;
    }

    function consult(pos){
        if(map[pos] != undefined) return map[pos];
        aux = Math.max(arr[pos-1], arr[pos+1]);
        if(aux < arr[pos]){
            map[pos] = 0;
            return 0;
        }
        map[pos] = aux - arr[pos] + 1;
        return map[pos];
    }

    first = calculate(arr);

    if(arr.length%2 == 1){
        return first;
    }

    let min = first;
    let atual = first;
    let old_val, new_val;
    for(let i = n-3; i >= 1; i-=2){
        old_val = consult(i);
        new_val = consult(i+1);
        atual = atual - old_val + new_val;
        if(atual < min) min = atual;
    }
    return min;

}

function go(h)
{
    let n = h.length;
    if (n % 2 == 1)
    {
        let s = 0;
        for (let i = 1; i < n; i += 2)
        {
            s += Math.max(h[i], h[i+1] + 1, h[i - 1] + 1) - h[i]
        }
        return s;
    }
    else
    {
        let oddpS = [0];
        for (let i = 1; i < n - 1; i += 2)
        {
            oddpS.push(Math.max(h[i], h[i+1] + 1, h[i - 1] + 1) - h[i] + oddpS[oddpS.length - 1])
        }
        let evenpS = [0]
        for (let i = n-2; i>0; i -= 2)
        {
            evenpS.push(Math.max(h[i], h[i+1] + 1, h[i - 1] + 1) - h[i] + evenpS[evenpS.length - 1])
        }
        let min = oddpS[0] + evenpS[evenpS.length - 1];
        for (let i = 1; i < oddpS.length; i ++)
        {
            let test = oddpS[i] + evenpS[evenpS.length - i - 1];
            if (test < min)
            {
                min = test;
            }
        }
        return min;
    }
}

let input = '';
process.stdin.on('data', c => input += c)
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = input.split(EOL); /*your input text, split by lines*/
    let cases = parseInt(lines[0])
    for (let caseNum = 0; caseNum < cases; caseNum ++)
    {
        let h = lines[caseNum * 2 + 2].split(" ").map(x => parseInt(x))
        console.log(go(h))
    }
})

'use strict';

function solve(n, a) {
  if (n & 1) {
    let sum = 0;
    for (let i = 1; i < n; i += 2) {
      const num = Math.max(a[i - 1], a[i + 1]);
      if (a[i] <= num) sum += num - a[i] + 1;
    }
    return sum;
  }
  const l = new Array(n).fill(0),
        r = new Array(n).fill(0);
  for (let i = 1; i < n; i += 2) {
    var _l, _l2;
    const num = Math.max(a[i - 1], a[i + 1]);
    if (a[i] <= num) l[i] = ((_l = l[i - 2]) !== null && _l !== void 0 ? _l : 0) + num - a[i] + 1;else l[i] = (_l2 = l[i - 2]) !== null && _l2 !== void 0 ? _l2 : 0;
  }
  for (let i = n - 2; i >= 0; i -= 2) {
    var _r, _r2;
    const num = Math.max(a[i - 1], a[i + 1]);
    if (a[i] <= num) r[i] = ((_r = r[i + 2]) !== null && _r !== void 0 ? _r : 0) + num - a[i] + 1;else r[i] = (_r2 = r[i + 2]) !== null && _r2 !== void 0 ? _r2 : 0;
  }
  let res = Infinity;
  for (let i = 1; i < n; i += 2) {
    var _l3, _r3;
    res = Math.min(res, ((_l3 = l[i - 2]) !== null && _l3 !== void 0 ? _l3 : 0) + ((_r3 = r[i + 1]) !== null && _r3 !== void 0 ? _r3 : 0));
  }
  return res;
}

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

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

var n = 0;
    var seq = [];
    function calc(i) {
        return Math.max(Math.max(0, seq[i-1] + 1 - seq[i], seq[i+1] + 1 - seq[i]));;
    }

    var tests = parseInt(readline());
    for (var t=0; t<tests;t++) {
        n = parseInt(readline());
        seq = readline().split(' ').map(x=>parseInt(x));
        var ans = 0;
        if (n & 1) {
            for (var i = 1; i < n-1;i += 2) {
                ans += calc(i);
            }
        } else {
            var adds = [];
            for (var i = 1; i < n-1; i++) {
                adds.push(calc(i));
            }
            var runningSum = 0;
            for (var i = 0; i < adds.length; i+=2) {
                runningSum += adds[i];
            }
            ans = runningSum;
            for (var i = adds.length-1; i > 0; i-=2) {
                runningSum = runningSum - adds[i-1] + adds[i];
                ans = Math.min(ans, runningSum);
            }
        }
        print(ans);
    }


const readline = require('readline')

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

function solve(n, str) {
    let cq = 0
    for (let i = 0; i < str.length; i++) {
        if (str[i] === 'Q') {
            cq++
        } else {
            if (cq > 0) cq--
        }
    }
    return cq === 0 ? 'Yes' : 'No'
}

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++){
		nl.num();
		let l = nl.line();
		let flag = l.substring(0,1) === 'Q' && l.substring(l.length-1) === 'A';
		let lag = 0;
		l.trim().split('').forEach(e => {
			if (e === "Q"){
				lag--;
			} else {
				if (lag < 0) {
					lag++;
				}
			}

		});
		ans.push(flag && lag === 0);
	}
	console.log(ans.map(x => x?"Yes":"No").join('\n'));
};

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

let buf='';

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

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 s=line[2*_];
        // console.log(n,s);
        let c1=0,c2=0;
        flag=true;
        for(let i=n-1;i>=0;i--)
        {
            if(s[i]==='Q') c1++;
            else c2++;
            if(c1>c2) flag=false;
        }
        if(flag) console.log("Yes");
        else console.log("No");
    }
})

let buf='';

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

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 s=line[2*_];
        // console.log(n,s);
        let c1=0,c2=0;
        flag=true;
        for(let i=n-1;i>=0;i--)
        {
            if(s[i]==='Q') c1++;
            else c2++;
            if(c1>c2) flag=false;
        }
        if(c1>c2) flag=false;
        if(s[n-1]==='Q') flag=false;
        if(flag) console.log("Yes");
        else console.log("No");
    }
})

let index = 0;

require('readline').createInterface({
    input: process.stdin
}).on('line', (line) => {
    if(index > 0 && index % 2 == 0) {
        solve(line)
    }

    // console.log('index', index)
    index++;
});

function solve(str) {
    let n = 0;

    for(let i = 0; i < str.length ; i++) {
        if(str[i] == "Q") {
            n++;
        } else {
            n--;
            if(n < 0) {
                n = 0
            }
        }
    }

    if(n === 0) {
        console.log('Yes');
    } else {
        console.log('No')
    }
}

let index = 0;

require('readline').createInterface({
    input: process.stdin
}).on('line', (line) => {
    if(index > 0 && index % 2 == 0) {
        solve(line)
    }

    index++;
});

function solve(str) {
    const queue = [];

    for(let i = 0; i < str.length ; i++) {
        if(str[i] == "Q") {
            queue.push("Q");
        } else {
            queue.pop()
        }
    }

    if(queue.length === 0) {
        console.log('Yes');
    } else {
        console.log('No')
    }
}

let index = 0;

require('readline').createInterface({
    input: process.stdin
}).on('line', (line) => {
    if(index > 0 && index % 2 == 0) {
        solve(line)
    }

    index++;
});

function solve(str) {
    const queue = [];
    let isSolvable = true;

    for(let i = 0; isSolvable && i < str.length ; i++) {
        if(str[i] == "Q") {
            queue.push("Q");
        } else {
            const front = queue.pop()
        }
    }

    if(isSolvable && queue.length === 0) {
        console.log('Yes');
    } else {
        console.log('No')
    }
}

'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 evaluateBoard(board)
{

}

function main() {

    let t = parseInt(readLine());

    while(t--)
    {
        const n = parseInt(readLine());

        let qas = readLine().split("");
        qas.pop()
        //console.log(qas)
        let count=0

        for (let i=0;i<n;i++)
        {
            if(qas[i]=="Q")
            {
                count++;
            }
            else
            {
                count--;
            }
            if(count<0)
                count=0;
        }
        if(count>0)
            console.log("No")
        else
            console.log("Yes")

    }
}

"use strict";
/*
5
4
QQAA
4
QQAQ
3
QAA
1
Q
14
QAQQAQAAQQQAAA

Yes
No
Yes
No
Yes

*/
exports.__esModule = true;
var readline_1 = require("readline");
function countChar(s, char) {
	var count = 0;
	for (var _i = 0, s_1 = s; _i < s_1.length; _i++) {
		var i = s_1[_i];
		if (i === char) {
			count++;
		}
	}
	return count;
}
function processTheSequence(lines) {
	var testCases = Number(lines[0]) * 2;
	var sequenceLen;
	var sequence;
	// let nOfQ: number;
	// let nOfA: number;
	for (var i = 1; i < testCases; i++) {
		var pendingQuestions = 0;
		sequenceLen = Number(lines[i]);
		sequence = lines[++i];
		// nOfA = countChar(sequence, "A");
		// nOfQ = countChar(sequence, "Q");
		// console.log(nOfA);
		// console.log(nOfQ);
		for (var _i = 0, sequence_1 = sequence; _i < sequence_1.length; _i++) {
			var j = sequence_1[_i];
			// console.log(j);
			if (j === "Q") {
				pendingQuestions += 1;
			} else if (j === "A" && pendingQuestions > 0) {
				pendingQuestions -= 1;
			}
		}
		// console.log(pendingQuestions);
		if (pendingQuestions === 0) {
			console.log("Yes");
		} else {
			console.log("No");
		}
	}
}
var rl = readline_1.createInterface(process.stdin, process.stdout);
var input = [];
rl.on("line", function (line) {
	return input.push(line);
}).on("close", function () {
	return processTheSequence(input);
});

let ryan = '';//.map(saer).sort(function(a, a){return a - a})
process.stdin.on('data', c => ryan += c);
process.stdin.on('end', () => {
    const {EOL} = require('os');
    const lines = ryan.split(EOL);
    var n = lines[0], e = 0
    for(i = 1; i <= n * 2; i++){
        if(i % 2 == 1){
            e = lines[i]
        }else{
            var a = lines[i].split(''), s = 0
            for(j = 0; j < e; j++){
                if(a[j] == 'Q'){
                    s++
                }else{
                    s = Math.max(0, s - 1)
                }
            }
            console.log(s === 0 ? 'YES' : 'NO')
        }
    }
});

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('');
            var a = 0;
            for(j = 0; j < n; j++){
                if(s[j] == 'Q'){
                    a++;
                }else{
                    a = Math.max(0, a - 1);
                }
            }
            console.log(a === 0 ? 'YES' : 'NO');
        }
    }
});

'use strict';

var fs = require('fs');

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

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

function solve(read) {
  const [rn, rb, rns, re, rbs] = convertInput(read);
  const n = rn(),
        s = read();
  let l = 0,
      r = 0;
  for (let i = 0; i <= n; i++) {
    if ((i === n || s[i] === 'Q') && s[i - 1] === 'A') {
      if (r > l) {
        r = 0, l = 0;
      }
    }
    if (i < n) {
      if (s[i] === 'Q') l++;else r++;
    }
  }
  if (r !== l) return 'No';
  return 'Yes';
}
function convertInput(read) {
  const rn = () => Number(read());
  const rb = () => BigInt(read());
  const rns = () => read().split(/\s+/).map(Number);
  const re = () => read().split(/\s+/).map(s => Number(s) - 1);
  const rbs = () => read().split(/\s+/).map(BigInt);
  return [rn, rb, rns, re, rbs];
}
function main(r) {
  try {
    let t = Number(r());
    let res = new Array(t);
    let limit = 0;
    for (let i = 0; i < t; i++) {
      var _solve;
      const s = (_solve = solve(r)) !== null && _solve !== void 0 ? _solve : '';
      if (t < limit) {
        process.stdout.write(s.toString());
        process.stdout.write('\n');
      } else {
        res[i] = s;
      }
    }
    if (t >= limit) {
      return res.join('\n');
    } else {
      return '';
    }
  } catch (error) {
    console.log(error);
  }
}

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

var chats = readline();

for (var i = 0; i < chats; i++) {
  computarChat();
}

function computarChat() {
  var numerodemensagens = Number(readline());
  var mensagems = readline().split("");

  var questoesAResponder = 0;

  for (var i = 0; i < numerodemensagens; i++) {
    var mensagem = mensagems[i];
    if (mensagem === "Q") {
      questoesAResponder += 1;
    }
    if (mensagem === "A" && questoesAResponder > 0) {
      questoesAResponder -= 1;
    }
  }

  // var questoesAResponder = mensagems.filter(function (mensagem) {
  //   return mensagem === "Q";
  // });
  // var respostas = mensagems.filter(function (mensagem) {
  //   return mensagem === "A";
  // });

  // var terminoucomanswer = mensagems[mensagems.length - 1] === "A";

  // // print(terminoucomanswer);

  if (!questoesAResponder) {
    print("Yes");
  } else {
    print("No");
  }
}

const x = readline(); // first line

for(var i = 0 ; i < x ; i++) {
  var length = readline(); // skip line
  var inp = readline().toLowerCase();

  var func = str => {
    if (str.includes('qa')) {
      str = str.replace('qa', '');
      return func(str);
    } else {
      return str.includes('q') ? 'No' : 'Yes';
    }
  };

  print(func(inp));
}

var groups = parseInt(readline(), 10)
for(var i = 0; i < groups; i++) {
    var len = parseInt(readline(), 10)
    var dialog = readline().split("")
    var q = 0;
    for (var j = 0; j < len; j++) {
        if (dialog[j] === "Q") q = q + 1
        if (dialog[j] === "A" && q > 0) q = q - 1
    }
    var res = q === 0 ? "Yes" : "No"
    print(res)
}

var t = readline();
for (var i = 0; i < t; ++i) {
  var n = readline(),
    counter = 0,
    input = readline().split("");
    for(var j = 0 ; j < n ; ++j){
    if(input[j] == 'Q' && counter >= 0){
        counter++;
    }
    else if(input[j] == 'Q' && counter < 0){
        counter = 1;
    }
    else{
        counter--;
    }
  }
  counter <= 0 ? print("YES") : print("NO");
}

function process(str) {
    var stack = [];

    for (var i = 0; i < str.length; i++) {
        var char = str[i];
        if (char === 'Q') {
            stack.push(char);
        } else {
            stack.pop();
        }
    }

    print(stack.length === 0 ? 'Yes': 'No');
}

var numOfCases = Number(readline());
for (var test = 0; test < numOfCases; test++) {
    var numOfChars = Number(readline());
    var str = readline();

    process(str);
}

var n = +readline();
for(var i = 0; i < n; i++) {
  var k = +readline();
  var str = readline();
  var count = 0;
  for(var j = 0; j < k; j++) {
    if(str[j] === 'Q') {
      count++;
    }
    if(str[j] === 'A' && count) {
      count--;
    }
  }
  print(count !== 0 ? 'No' : 'Yes');
}

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++){
		nl.num();
		let l = nl.line();
		let flag = l.substring(0,1) === 'Q' && l.substring(l.length-1) === 'A';
		let lag = 0;
		l.trim().split('').forEach(e => {
			lag += (e === "Q"?-1:1);
			if (lag > 0) flag = false;

		});
		ans.push(flag);
	}
	console.log(ans.map(x => x?"Yes":"No").join('\n'));
};

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

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++){
		nl.num();
		let l = nl.line();
		let flag = l.substring(0,1) === 'Q' && l.substring(l.length-1) === 'A';
		let lag = 0;
		l.trim().split('').forEach(e => {
			lag += (e === "Q"?-1:1);
			if (lag > 0) lag = false;

		});
		ans.push(flag);
	}
	console.log(ans.map(x => x?"Yes":"No").join('\n'));
};

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

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++){
		nl.num();
		let l = nl.line();
		let flag = 0;
		l.trim().split('').forEach(e => flag += (e === "Q"?-1:1));
		ans.push(flag >= 0  && l.substring(0,1) !== l.substring(l.length-1));
	}
	console.log(ans.map(x => x?"Yes":"No").join('\n'));
};

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

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++){
		nl.num();
		let l = nl.line();
		let flag = 0;
		l.trim().split('').forEach(e => flag += (e === "Q"?-1:1));
		console.log(flag);
		ans.push(flag >= 0  && l.substring(0,1) !== l.substring(l.length-1));
	}
	console.log(ans.map(x => x?"Yes":"No").join('\n'));
};

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

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++){
		nl.num();
		let l = nl.line();
		let flag = 0;
		l.split('').forEach(e => flag += (e === "Q"?-1:1));
		ans.push(flag >= 0  && l.substring(0,1) !== l.substring(l.length-1));
	}
	console.log(ans.map(x => x?"Yes":"No").join('\n'));
};

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

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++){
		nl.num();
		let l = nl.line();
		ans.push(l.substring(0,1) !== l.substring(l.length-1));
	}
	console.log(ans.map(x => x?"Yes":"No").join('\n'));
};

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

let buf='';

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

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 s=line[2*_];
        // console.log(n,s);
        let c1=0,c2=0;
        flag=true;
        // for(let i=0;i<n;i++)
        // {
        //     if(s[i]==='Q') c1++;
        //     else c2++;
        //     if(c1<c2) flag=false;
        // }
        if(c1>c2) flag=false;
        if(s[n-1]==='Q') flag=false;
        if(flag) console.log("Yes");
        else console.log("No");
    }
})

let buf='';

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

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 s=line[2*_];
        // console.log(n,s);
        let c1=0,c2=0;
        flag=true;
        for(let i=0;i<n;i++)
        {
            if(s[i]==='Q') c1++;
            else c2++;
            // if(c1>c2) flag=false;
        }
        // if(c1>c2) flag=false;
        if(s[n-1]==='Q') flag=false;
        if(flag) console.log("Yes");
        else console.log("No");
    }
})

let buf='';

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

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 s=line[2*_];
        // console.log(n,s);
        let c1=0,c2=0;
        flag=true;
        for(let i=0;i<n;i++)
        {
            if(s[i]==='Q') c1++;
            else c2++;
            // if(c1>c2) flag=false;
        }
        if(c1>c2) flag=false;
        if(flag) console.log("Yes");
        else console.log("No");
    }
})

'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 evaluateBoard(board)
{

}

function main() {

    let t = parseInt(readLine());

    while(t--)
    {
        const n = parseInt(readLine());

        let qas = readLine().split("");
        qas.pop()
        //console.log(qas)
        let count=0

        for (let i=0;i<n;i++)
        {
            if(qas[i]=="Q")
                count++;
            else
                count--;
        }
        if(qas[qas.length-1]=="Q")
        {
            console.log("No")
            continue;
        }
        if(count>0)
            console.log("No")
        else
            console.log("Yes")

    }
}

'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 evaluateBoard(board)
{

}

function main() {

    let t = parseInt(readLine());

    while(t--)
    {
        const n = parseInt(readLine());

        let qas = readLine().split("");
        qas.pop()
        //console.log(qas)
        let count=0

        for (let i=0;i<n;i++)
        {
            if(qas[i]=="Q")
                count++;
            else
                count--;
        }
        if(count>0)
            console.log("No")
        else
            console.log("Yes")

    }
}

"use strict";
/*
5
4
QQAA
4
QQAQ
3
QAA
1
Q
14
QAQQAQAAQQQAAA

Yes
No
Yes
No
Yes

*/
exports.__esModule = true;
var readline_1 = require("readline");
function countChar(s, char) {
	var count = 0;
	for (var _i = 0, s_1 = s; _i < s_1.length; _i++) {
		var i = s_1[_i];
		if (i === char) {
			count++;
		}
	}
	return count;
}
function processTheSequence(lines) {
	var testCases = Number(lines[0]) * 2;
	var sequenceLen;
	var sequence;
	var nOfQ;
	var nOfA;
	for (var i = 1; i < testCases; i++) {
		sequenceLen = Number(lines[i]);
		sequence = lines[++i];
		nOfA = countChar(sequence, "A");
		nOfQ = countChar(sequence, "Q");
		// console.log(nOfA);
		// console.log(nOfQ);
		if (nOfA === nOfQ || nOfA > nOfQ) {
			console.log("Yes");
		} else {
			console.log("No");
		}
	}
}
var rl = readline_1.createInterface(process.stdin, process.stdout);
var input = [];
rl.on("line", function (line) {
	return input.push(line);
}).on("close", function () {
	return processTheSequence(input);
});

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 str = lines[l++]
        output[i] = solve(n, str)
    }
    console.log(output.join('\n'))
// })()
})

function solve(n, str) {
    let cq = 0, ca = 0
    for (let i = 0; i < str.length; i++) {
        if (str[i] === 'Q') {
            cq++
        } else {
            ca++
        }
    }
    return ca >= cq ? 'Yes' : 'No'
}

var chats = readline();

for (var i = 0; i < chats; i++) {
  computarChat();
}

function computarChat() {
  var numerodemensagens = Number(readline());
  var mensagems = readline().split("");

  var questoesAResponder = mensagems.filter(function (mensagem) {
    return mensagem === "Q";
  });
  var respostas = mensagems.filter(function (mensagem) {
    return mensagem === "A";
  });

  var terminoucomanswer = mensagems[mensagems.length - 1] === "A";

  // print(terminoucomanswer);

  if (respostas.length >= questoesAResponder.length && terminoucomanswer) {
    print("Yes");
  } else {
    print("No");
  }
}

const x = readline(); // first line

for(var i = 0 ; i < x ; i++) {
  readline(); // skip line
  var inp = readline().toLowerCase().split('');
  var func = arr => {
    if (inp[0] == 'a') return 'No';
    var halfLength = Math.floor(arr.length/2);
    var questions = arr.filter(l => l == 'q');
    return questions.length <= halfLength ? 'Yes' : 'No'
  }

  print(func(inp));
}

const x = readline(); // first line

for(var i = 0 ; i < x ; i++) {
  readline(); // skip line
  var inp = readline().toLowerCase().split('');
  var func = arr => {
    var initLength = arr.length;
    var questions = arr.filter(l => l == 'q');
    return questions.length <= Math.floor(initLength/2) ? 'Yes' : 'No'
  }
  print(func(inp));
}

var groups = parseInt(readline(), 10)
for(var i = 0; i < groups; i++) {
    var length_dialog = readline()
    var dialog = readline().split("")
    if (dialog[0] !== "Q"|| dialog[dialog.length - 1] !== "A") {
        print("NO")
        continue
    }
    var a = dialog.filter(d => d === "A").length
    var q = dialog.filter(d => d === "Q").length
    var res = a >= q ? "YES" : "NO"
    print(res)
}

var groups = parseInt(readline(), 10)
for(var i = 0; i < groups; i++) {
    var length_dialog = readline()
    var dialog = readline().split("")
    if (dialog[0] !== "Q") {
        print("NO")
        continue
    }
    var a = dialog.filter(d => d === "A").length
    var q = dialog.filter(d => d === "Q").length
    var res = a >= q ? "YES" : "NO"
    print(res)
}

var groups = readline()
for(var i = 0; i < groups; i++) {
    var len = readline()
    var dialog = readline().split("")
    var a_number = dialog.filter(d => d === "A").length
    var q_number = dialog.filter(d => d === "Q").length
    var res = a_number >= q_number ? "YES" : "NO"
    print(res)
}

var t = readline();
for (var i = 0; i < t; ++i) {
  var n = readline(),
    qCounter = 0,
    aCounter = 0,
    input = readline().split("");
  if (input[input.length - 1] == "Q") {
    print("NO");
  } else {
    for (var j = 0; j < n; ++j) {
      input[j] == "Q" ? qCounter++ : aCounter++;
    }
    aCounter >= qCounter ? print("YES") : print("NO");
  }
}

var t = readline();
    for(var i = 0 ; i < t ; ++i){
        var n = readline(), qCounter = 0 , aCounter = 0,
            input = readline().split('');
            for(var j = 0 ; j < n ; ++j){
                input[j] == 'Q' ? qCounter++ : aCounter++;
    }
            aCounter >= qCounter ? print("YES") : print("NO");
}

var numOfChars = Number(readline());
var str = readline();

var stack = [];

for (var i = 0; i < str.length; i++) {
    var char = str[i];
    if (char === 'Q') {
        stack.push(char);
    } else {
        stack.pop();
    }
}

print(stack.length === 0 ? 'Yes': 'No');


'use strict';

function solve(n, a) {
  if (n & 1) return 'NO';
  a.sort((a, b) => a - b);
  let res = [];
  for (let i = 0, j = n / 2; j < n; i++, j++) {
    res.push(a[i], a[j]);
  }
  for (let i = 0; i < n; i++) {
    let l = (i - 1 + n) % n,
        r = (i + 1) % n;
    if (res[i] > res[l] && res[i] > res[r] || res[i] < res[l] && res[i] < res[r]) continue;
    return 'NO';
  }
  return `YES\n${res.join(' ')}`;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res.push(solve(n, a));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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

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

function Main(){
    // test case in nodeJs
	var t = nextInt();
	while(hasNext()){
		solve();
	}
}

function solve() {
	const n = nextInt();

	const arr = nextIntArray(n);

	if (n % 2 === 1) {
		myout("NO");
		return;
	}

	arr.sort((a, b) => a - b);
	let median;

	if (arr.length % 2 === 0) {
		median = (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
	} else {
		median = arr[(arr.length - 1) / 2];
	}

	const mins = arr.slice(0, arr.length / 2 );
	const maxs = arr.slice(arr.length / 2 );

	const res = [];

	let j = 0, k = 0;

	for (let i = 0; i < arr.length; i++) {
		if (i % 2 === 0) {
			if (i >= 1 && res[i - 1] === mins[j]) {
				myout("NO");
				return;
			}
			res[i] = mins[j];
			j++;
		} else {
			if (i >= 1 && res[i - 1] === maxs[k]) {
				myout("NO");
				return;
			}
			res[i] = maxs[k];
			k++;
		}
	}

	myout("YES");
	myout(res.join(" "));
}

'use strict';
// HEADER:
const print = function(arg){
  let str = arg;
  if (arguments.length>1)
    str = Array.prototype.slice.call(arguments).join(' ');
  process.stdout.write(str+'\n');
};
let IS_MULTITEST, testN, tests;
const pcalc = (testN, toPrint)=>{
  let res = CALC(testN);
  if (Array.isArray(res)){
    toPrint.push(res.join(' '));
  } else if (Number.isFinite(res) || typeof res=='string'){
    toPrint.push(res+'');
  }
  if (process.env.DEBUG && toPrint.length){
    let ans = toPrint.pop();
    print(ans);
    let expected = tests[testN-1];
    if (expected){
      if (expected==ans)
        console.log('\x1b[32m%s\x1b[0m', 'correct');
      else {
        console.log('\x1b[31m%s\x1b[0m', 'wrong, expected:', expected);
      }
    }
  }
};

const main = ()=>{
  let toPrint = [];
  L('\nSolving:');
  if (IS_MULTITEST){
    let T = +readline()
    for (testN=1; testN<=T; testN++)
      pcalc(testN, toPrint);
  } else {
    pcalc(1, toPrint);
  }
  if (toPrint.length){
    print(toPrint.join('\n'));
  }
};

const lines = [];
const rl = require('readline').createInterface({
   input: process.stdin, output: process.stdout});
rl.on('line', line=>{
  lines.push(line);
});
rl.on('close', main);
let rli = 0;
const readline = ()=>lines[rli++];
const L = process.env.DEBUG ? console.log : ()=>{};
const LT = obj=>L(`\nTest #${testN}`, obj);

const ra = ()=>readline().split(' ').map(a=>+a)
const pa = arr=>print(arr.join(' '));

tests = [
``, // Test #1
``, // Test #2
``, // Test #3
``, // Test #4
``, // Test #5
];

// SOLUTION:
IS_MULTITEST = true;

const CALC = (testN)=>{
  // READING:
  let [n, m] = ra();
  let A = ra();
  LT({n, A});
  // PROCESSING:
  if (n%2==1)
    return 'NO'
  let ans = 0;
  A.sort((a, b)=>a-b);
  let arr = [];
  for (let i=0; i<n/2; i++){
    arr.push(A[i]);
    arr.push(A[i+n/2]);
  }
  for (let i=0; i<n; i+=2){
    if (arr[i]<arr[(i+n-1)%n] && arr[i]<arr[i+1])
      continue;
    return 'NO'
  }
  L({arr})
  return 'YES'+'\n'+arr.join(' ')
  let lower = A.slice(0, n/2);
  let higher = A.slice(n/2);
  L({A, lower, higher})
  return ans;
};

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{
            if(n % 2){
                console.log('NO');
                continue;
            }
            var b = Math.floor(n / 2);
            var flag = false;
            var a = lines[i].split(' ').map(Number).sort(function(a, b){return a - b});
            for(j = 1; j < b; j++){
                if(a[j] == a[j + b - 1]){
                    console.log('NO');
                    flag = true;
                    break;
                }
            }
            var ans = '';
            if(!flag){
                console.log('YES');
                for(j = 0; j < b; j++){
                    ans += a[j] + ' ' + a[j + b] + ' ';
                }
                console.log(ans);
            }
        }
    }
});

const solve  = (arr,n)=>{
     if(n%2){
          console.log("NO");
          return;
     }
     arr.sort((a,b)=>a-b);
     let res = [],i=0,j=0,k = Math.floor(n/2);
     while(i*2<n){
          res.push(arr[j]);
          if(k<n) res.push(arr[k]);
          j++;
          k++;
          i++;
     }
     let str = "";
     for(let i=0;i<n;i++){
          if(res[i]===res[(i+1)%n]){
               console.log("NO");
               return;
          }
          str+=res[i]+" ";
     }
     console.log("YES");
     console.log(str);
}
function main() {
  const fs = require("fs");
  const input = fs.readFileSync(0, "utf8").trim().split("\n");
  let line = 0;
  function readline() {
    return input[line++];
  }
  let t = parseInt(readline());
  for (let i = 0; i < t; i++) {
       let n = parseInt(readline());
       let arr = readline().trim().split(" ").map(cur=>parseInt(cur));
       solve(arr,n);
  }
}
main();

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

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

/*---------------------------------------------------*/

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

const getDigits = (x) => {
    let digits = new Array(10).fill(false);
    let len = 0;
    while (x) {
        len++;
        digits[x % 10n] = true;
        x /= 10n;
    }
    return [digits, len];
}

const getLen = (x) => {
    let str = x.toString(10);
    return str.length;
}

const calc = (t)=>{
    /* read */
    let n = readline();
    let a = ra();

    a.sort((x, y) => x - y);

    let b = new Array(n);

    let j = 0;

    for (let i = 0; i < n; i += 2) {
        b[i] = a[j++];
    }

    for (let i = 1; i < n; i += 2) {
        b[i] = a[j++];
    }

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

    for (let i = 0; i < n; i++) {
        let next = (i + 1) % n;
        let prev = (n + i - 1) % n;

        let x = (b[prev] > b[i]) && (b[i] < b[next]);
        let y = (b[prev] < b[i]) && (b[i] > b[next]);

        if (!(x || y)) {
            // console.log(`DEBUG prev ${prev}, i ${i}, next ${next}`);
            return 'NO'
        }
        // console.log(`DEBUG mx ${mx}, a[mx] ${a[mx]}, i `, i);
    }

    return 'YES\n' + b.join(' ');
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
function lowerBound(a, x) {
    let lo = 0;
    let hi = a.length;
    while (lo < hi) {
        let mid = lo + Math.trunc((hi - lo) / 2);
        if (a[mid] >= x) {
            hi = mid;
        }
        else {
            lo = mid + 1;
        }
    }
    return hi;
}
const INIT = -1;
const INF = Infinity;
let n;
let a;
function solve() {
    if ((n % 2) != 0) {
        return false;
    }
    a.sort((i, j) => i - j);
    let m = n / 2;
    for (let i = 1; i + m < n; i++) { // caution
        // printf("a[%d] %d a[%d] %d\n", i, a[i], i + m - 1, a[i + m - 1]);
        if (a[i] == a[i + m - 1]) {
            return false;
        }
    }
    const ans = af(n);
    let j = m;
    for (let i = 0; i + m < n; i++) {
        ans[i + i] = a[i];
        ans[i + i + 1] = a[i + m];
    }
    process.stdout.write('YES\n');
    process.stdout.write(ans.join(' '));
    process.stdout.write('\n');
    return true;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        if (!solve()) {
            printf("NO\n");
        }
    }
}

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

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

/*---------------------------------------------------*/

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

const getDigits = (x) => {
    let digits = new Array(10).fill(false);
    let len = 0;
    while (x) {
        len++;
        digits[x % 10n] = true;
        x /= 10n;
    }
    return [digits, len];
}

const getLen = (x) => {
    let str = x.toString(10);
    return str.length;
}

const calc = (t)=>{
    /* read */
    let n = readline();
    let a = ra();

    a.sort();

    let b = new Array(n);

    let j = 0;

    for (let i = 0; i < n; i += 2) {
        b[i] = a[j++];
    }

    for (let i = 1; i < n; i += 2) {
        b[i] = a[j++];
    }

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

    for (let i = 0; i < n; i++) {
        let next = (i + 1) % n;
        let prev = (n + i - 1) % n;

        let x = (b[prev] > b[i]) && (b[i] < b[next]);
        let y = (b[prev] < b[i]) && (b[i] > b[next]);

        if (!(x || y)) {
            // console.log(`DEBUG prev ${prev}, i ${i}, next ${next}`);
            return 'NO'
        }
        // console.log(`DEBUG mx ${mx}, a[mx] ${a[mx]}, i `, i);
    }

    return 'YES\n' + b.join(' ');
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

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

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

/*---------------------------------------------------*/

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

const getDigits = (x) => {
    let digits = new Array(10).fill(false);
    let len = 0;
    while (x) {
        len++;
        digits[x % 10n] = true;
        x /= 10n;
    }
    return [digits, len];
}

const getLen = (x) => {
    let str = x.toString(10);
    return str.length;
}

const calc = (t)=>{
    /* read */
    let n = readline();
    let a = ra();

    a.sort();

    let b = new Array(n);

    let j = 0;

    for (let i = 0; i < n; i += 2) {
        b[i] = a[j++];
    }

    for (let i = 1; i < n; i += 2) {
        b[i] = a[j++];
    }

    console.log('DEBUG b', b);

    for (let i = 0; i < n; i++) {
        let next = (i + 1) % n;
        let prev = (n + i - 1) % n;

        let x = (b[prev] > b[i]) && (b[i] < b[next]);
        let y = (b[prev] < b[i]) && (b[i] > b[next]);

        if (!(x || y)) {
            // console.log(`DEBUG prev ${prev}, i ${i}, next ${next}`);
            return 'NO'
        }
        // console.log(`DEBUG mx ${mx}, a[mx] ${a[mx]}, i `, i);
    }

    return 'YES\n' + b.join(' ');
};

function main() {
    let T = +readline();
    let out = [];
    for (let t = 1; t <= T; t++){
        out.push(calc(t));
        // process.stdout.write(`${calc(t)}\n`);
    }
    process.stdout.write(out.join('\n')+'\n');
}

'use strict';
const readline = require('readline');
const util = require('util');
const lineReader = readline.createInterface({
    input: process.stdin,
});
let inputPos = 0;
const inputWords = [];
lineReader.on('line', (line) => {
    inputWords.push.apply(inputWords, line.split(' ').filter(s => s != ''));
});
lineReader.on('close', main);
function check(b) {
    if (!b) {
        process.stderr.write(`${new Error().stack}\n`);
        process.exit(-1);
    }
}
function printf(...args) {
    process.stdout.write(util.format(...args));
}
function nextInt() {
    return Math.trunc(Number(inputWords[inputPos++]));
}
function nextStr() {
    return inputWords[inputPos++];
}
function af(l) {
    return Array.from({ length: l });
}
function lowerBound(a, x) {
    let lo = 0;
    let hi = a.length;
    while (lo < hi) {
        let mid = lo + Math.trunc((hi - lo) / 2);
        if (a[mid] >= x) {
            hi = mid;
        }
        else {
            lo = mid + 1;
        }
    }
    return hi;
}
const INIT = -1;
const INF = Infinity;
let n;
let a;
function solve() {
    if ((n % 2) != 0) {
        return false;
    }
    a.sort((i, j) => i - j);
    let m = n / 2;
    for (let i = 1; i + m <= n; i++) {
        if (a[i] == a[i + m - 1]) {
            return false;
        }
    }
    const ans = af(n);
    let j = m;
    for (let i = 0; i + m < n; i++) {
        ans[i + i] = a[i];
        ans[i + i + 1] = a[i + m];
    }
    process.stdout.write('YES\n');
    process.stdout.write(ans.join(' '));
    process.stdout.write('\n');
    return true;
}
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        n = nextInt();
        a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        if (!solve()) {
            printf("NO\n");
        }
    }
}

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

function Main(){
    // test case in nodeJs
	var t = nextInt();
	while(hasNext()){
		solve();
	}
}

function solve() {
	const n = nextInt();

	const arr = nextIntArray(n);

	if (n % 2 === 1) {
		myout("NO");
		return;
	}

	arr.sort((a, b) => a - b);
	let median;

	if (arr.length % 2 === 0) {
		median = (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
	} else {
		median = arr[(arr.length - 1) / 2];
	}

	const mins = [];
	const maxs = [];

	for (let i = 0; i < arr.length; i++) {
		if (arr[i] < median) {
			mins.push(arr[i]);
		} else {
			maxs.push(arr[i]);
		}
	}

	if (Math.abs(maxs.length - mins.length) > 1) {
		myout("NO");
		return;
	}

	const res = [];

	let j = 0, k = 0;

	for (let i = 0; i < arr.length; i++) {
		if (i % 2 === 0) {
			res[i] = mins[j];
			j++;
		} else {
			res[i] = maxs[k];
			k++;
		}
	}

	myout("YES");
	myout(res.join(" "));
}

'use strict';

function solve(n, a) {
  a.sort((a, b) => a - b);
  let res = [];
  for (let i = 0, j = n - 1; i <= j; i++, j--) {
    if (i === j) {
      res.push(a[i]);
    } else res.push(a[i], a[j]);
  }
  for (let i = 0; i < n; i++) {
    let l = (i - 1 + n) % n,
        r = (i + 1) % n;
    if (res[i] > res[l] && res[i] > res[r] || res[i] < res[l] && res[i] < res[r]) continue;
    return 'NO';
  }
  return `YES\n${res.join(' ')}`;
}

async function main(read) {
  try {
    let res = [];
    let t = Number(await read());
    while (t--) {
      const n = Number(await read());
      const a = (await read()).split(' ').map(Number);
      res.push(solve(n, a));
    }
    console.log(res.join('\n'));
  } catch (error) {
    console.log(error);
  }
}

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