'use strict';

function solve(n, a) {
  let po = -1,
      pe = -1;
  for (let i = 0; i < n; i++) {
    if (a[i] & 1) {
      if (a[i] < po) return 'NO';
      po = a[i];
    } else {
      if (a[i] < pe) return 'NO';
      pe = a[i];
    }
  }
  return 'YES';
}

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

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 a = lines[i].split(' ').map(Number);
            var max = [0, 0];
            var flag = 0;
            for(j = 0; j < n; j++){
                var k = Math.floor(a[j] % 2);
                if(max[k] > a[j]){
                    flag = 1;
                    break;
                }
                max[k] = Math.max(max[k], a[j]);
            }
            console.log(flag == 1 ? 'NO' : 'YES');
        }
    }
});

'use strict';
 /*jslint node:true, browser:true, es6:true*/
const print = console.log
const E = {};
const lines = []
if (!process.env.JEST_WORKER_ID){
  const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout })
  rl.on('line', line => {
      lines.push(line);
  });
  rl.on('close', main)
}
let rli = 0;
function readline() {
    return lines[rli++];
}
const L = process.env.DEBUG ? console.log : ()=>{};

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

const calc = (n, A)=>{
  let odd = [];
  let even = []
  for (let a of A){
    if (a&1) odd.push(a); else even.push(a);
  }
  for (let i=0; i<odd.length-1; i++)
    if (odd[i]>odd[i+1])
      return false;
  for (let i=0; i<even.length-1; i++)
    if (even[i]>even[i+1])
      return false;
    return true;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let A = ra();
      L('ans')
      print(calc(n, A) ? 'yes' : 'no');
    }
}

E.calc = calc;

const readline = require('readline');

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

const it = rl[Symbol.asyncIterator]();

const main = async () => {
    const use_cases = await it.next();
    let t = use_cases.value;
    while(t--)
    {
        const n = Number((await it.next()).value);
        let arr = (await it.next()).value.split(' ').map( x => Number(x));
        let even_arr = [];
        let odd_arr = [];
        arr.forEach(element => {
            element%2 === 0 ? even_arr.push(element) : odd_arr.push(element)
        });
        let flag = false;
        let even_arr_length = even_arr.length;
        let odd_arr_length = odd_arr.length;
        let prev_even = even_arr_length > 0 && even_arr[0];
        let prev_odd = odd_arr_length > 0 && odd_arr[0];
        for(let i=1; i<even_arr_length;i++)
        {
            if(prev_even > even_arr[i])
            {
                flag = true;
                break;
            }
            prev_even = even_arr[i];
        }
        if(!flag)
        {
            for(let i=1; i<odd_arr_length;i++)
            {
                if(prev_odd > odd_arr[i])
                {
                    flag = true;
                    break;
                }
                prev_odd = odd_arr[i];
            }
        }
        console.log(flag===false ? 'Yes': 'No');
    }

}
main();

var tests = parseInt(readline());

for (var i = 0; i < tests; i++) {
  var n = parseInt(readline());
  var arr = readline()
    .split(" ")
    .map((i) => parseInt(i));

  var odd = null;
  var even = null;
  var posible = true;
  for (var j = 0; j < arr.length; j++) {
    if (arr[j] % 2 == 0) {
      if (even == null) even = arr[j];
      else {
        if (even > arr[j]) {
          posible = false;
          break;
        } else {
          even = arr[j];
        }
      }
    } else {
      if (odd == null) odd = arr[j];
      else {
        if (odd > arr[j]) {
          posible = false;
          break;
        } else {
          odd = arr[j];
        }
      }
    }
  }
  print(posible ? "Yes" : "No");
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let swappable = true;
        let highestOddNumber = 1;
        let highestEvenNumber = 2;

        for (let j=0; j<lengthOfArr-1; j++) {
            let a = arr[j];
            let b = arr[j+1];

            if (a % 2 === 0) {
                if (a > highestEvenNumber)
                    highestEvenNumber = a;
            }
            else {
                if (a > highestOddNumber)
                highestOddNumber = a;
            }

            if (b % 2 === 0) {
                if (b < highestEvenNumber) {
                    swappable = false;
                    break;
                }
            }
            else {
                if (b < highestOddNumber) {
                    swappable = false;
                    break;
                }
            }
        }

        console.log(swappable ? "YES" : "NO");
    }

//    console.log(Date.now() - startTime + " ms");
}

const solve = (n,arr)=>{
     let odd = [0];
     let even = [0];
     for(let i=0;i<n;i++){
          if(arr[i]%2){
               if(odd[odd.length-1]<=arr[i]) odd.push(arr[i]);
               else return "NO";
          }
          else{
               if(even[even.length-1]<=arr[i]) even.push(arr[i]);
               else return "NO";
          }
     }
     return "YES";
}
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));
       console.log(solve(n,arr));
  }
}
main();

'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++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const tests_count = parseInt(readline());
  for (var test = 0; test < tests_count; test++) {
    const n = parseInt(readline());
    const numbers = readline().split(" ").filter(s => s.trim().length !== 0).map(s => parseInt(s.trim()));
    console.log(canBeSorted(numbers) ? "Yes" : "No");
  }
}

function canBeSorted(items) {
  let maxEven = 0;
  let maxOdd = 0;
  for (let i = 0; i < items.length; i++)
    if (items[i] % 2 == 0)
      if (items[i] < maxEven)
        return false;
      else
        maxEven = items[i];
    else
      if (items[i] < maxOdd)
        return false;
      else
        maxOdd = items[i]

  return true;
}

"use strict";

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

let inputString = "";
let currentLine = 0;

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

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

	main();
});

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

function main() {
	const testCount = +readline();

	for (let j = 0; j < testCount; j++) {
		let arrayLength = +readline();
		let array = readline()
			.split(" ")
			.map((e) => +e);

		let possible = true;
		let biggestOdd = 0;
		let biggestEven = 0;
		let i = 0;
		while (i < array.length) {
			const a = array[i];

			if (a % 2) {
				if (a < biggestOdd) {
					possible = false;
					break;
				}
				biggestOdd = a > biggestOdd ? a : biggestOdd;
			} else {
				if (a < biggestEven) {
					possible = false;
					break;
				}
				biggestEven = a > biggestEven ? a : biggestEven;
			}

			i++;
		}

		console.log(possible ? "yes" : "no");
	}
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let swappable = true;
        let highestOddNumber = 1;
        let highestEvenNumber = 2;

        for (let j=0; j<lengthOfArr-1; j++) {
            let a = arr[j];
            let b = arr[j+1];

            if (a % 2 === 0) {
                if (a > highestEvenNumber)
                    highestEvenNumber = a;
            }
            else {
                if (a > highestOddNumber)
                highestOddNumber = a;
            }

            if (a > b) {
                if ((a + b) % 2 === 0) {
                    swappable = false;
                    break;
                }

                if (b % 2 === 0) {
                    if (b < highestEvenNumber) {
                        swappable = false;
                        break;
                    }
                    else if (b > highestEvenNumber)
                        highestEvenNumber = b;
                }
                else {
                    if (b < highestOddNumber) {
                        swappable = false;
                        break;
                    }
                    else if (b > highestOddNumber)
                        highestOddNumber = b;
                }
            }
        }

        console.log(swappable ? "YES" : "NO");
    }

//    console.log(Date.now() - startTime + " ms");
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let swappable = true;
        let highestOddNumber = 1;

        for (let a=0; a<lengthOfArr-1; a++) {
            if (arr[a] > arr[a+1]) {
                if ((arr[a] + arr[a+1]) % 2 === 0) {
                    swappable = false;
                    break;
                }

                if (arr[a+1] % 2 !== 0) {
                    if (arr[a+1] < highestOddNumber) {
                        swappable = false;
                        break;
                    }
                    else if (arr[a+1] > highestOddNumber) {
                        highestOddNumber = arr[a+1];
                    }
                }

                const temp = arr[a];
                arr[a] = arr[a+1];
                arr[a+1] = temp;
            }
        }

        console.log(swappable ? "YES" : "NO");
    }

//    console.log(Date.now() - startTime + " ms");
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let swappable = true;
        let highestOddNumber = 1;

        for (let a=0; a<lengthOfArr-1; a++) {
            if (arr[a] > arr[a+1]) {
                if ((arr[a] + arr[a+1]) % 2 === 0) {
                    swappable = false;
                    break;
                }

                if (arr[a+1] % 2 !== 0) {
                    if (arr[a+1] > highestOddNumber) {
                        swappable = false;
                        break;
                    }
                    else if (arr[a+1] > highestOddNumber) {
                        highestOddNumber = arr[a+1];
                    }
                }

                const temp = arr[a];
                arr[a] = arr[a+1];
                arr[a+1] = temp;
            }
        }

        console.log(swappable ? "YES" : "NO");
    }

//    console.log(Date.now() - startTime + " ms");
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let swappable = true;
        let highestOddNumber = null;

        for (let a=0; a<lengthOfArr-1; a++) {
            if (arr[a] % 2 !== 0 && (arr[a] > highestOddNumber || highestOddNumber === null))
                highestOddNumber = arr[a];

            if (arr[a+1] % 2 !== 0 && arr[a+1] < highestOddNumber && highestOddNumber !== null) {
                swappable = false;
                break;
            }

            if (arr[a] > arr[a+1]) {
                if ((arr[a] + arr[a+1]) % 2 === 0) {
                    swappable = false;
                    break;
                }
                const temp = arr[a];
                arr[a] = arr[a+1];
                arr[a+1] = temp;
            }
        }

        console.log(swappable ? "YES" : "NO");
    }

//    console.log(Date.now() - startTime + " ms");
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let swappable = true;
        let highestOddNumber = 1;

        for (let a=0; a<lengthOfArr-1; a++) {
            if (arr[a] % 2 !== 0 && arr[a] > highestOddNumber)
                highestOddNumber = arr[a];

            if (arr[a+1] % 2 !== 0 && arr[a+1] < highestOddNumber) {
                swappable = false;
                break;
            }

            if (arr[a] > arr[a+1]) {
                if ((arr[a] + arr[a+1]) % 2 === 0) {
                    swappable = false;
                    break;
                }
                const temp = arr[a];
                arr[a] = arr[a+1];
                arr[a+1] = temp;
            }
        }

        console.log(swappable ? "YES" : "NO");
    }

//    console.log(Date.now() - startTime + " ms");
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

function main() {
    const numOfTests = +(readline());

    for (let i=0; i<numOfTests; i++){
        const lengthOfArr = +(readline());
        let arr = readline().split(" ").map((string) => {
            return +(string);
        });

        let swappable = true;
        let highestOddNumber = 1;

        for (let a=0; a<lengthOfArr-1; a++) {
            if (arr[a] % 2 !== 0 && arr[a] > highestOddNumber)
                highestOddNumber = arr[a];

            if (arr[a] > arr[a+1] && (arr[a] + arr[a+1]) % 2 === 0) {
                swappable = false;
                break;
            }

            if (arr[a+1] % 2 !== 0 && arr[a+1] < highestOddNumber) {
                swappable = false;
                break;
            }
        }

        console.log(swappable ? "YES" : "NO");
    }

//    console.log(Date.now() - startTime + " ms");
}

const solve = (n,arr)=>{
     let obj = {};
     for(let i=0;i<n;i++) obj[arr[i]] = i;
     let res  = [...arr];
     res.sort((a,b)=>a-b);
     for(let i=0;i<n;i++){
          if(arr[i]!==res[i]){
               if((arr[i]+res[i])%2){
                    let j = obj[res[i]];
                    [arr[i],arr[j]] = [arr[j],arr[i]];
               }
               else return "NO";
          }
     }
     return "YES";
}
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));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
     let res  = [...arr];
     res.sort((a,b)=>a-b);
     for(let i=0;i<n;i++){
          if(arr[i]!==res[i]){
               if((arr[i]+res[i])%2===0) return "NO";
          }
     }
     return "YES";
}
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));
       console.log(solve(n,arr));
  }
}
main();

const solve = (n,arr)=>{
     for(let i=0;i<n-1;i++){
          if(arr[i]>arr[i+1]){
               if((arr[i]+arr[i+1])%2) [arr[i],arr[i+1]] = [arr[i+1],arr[i]];
               else return "NO";
          }
     }
     return "YES";
}
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));
       console.log(solve(n,arr));
  }
}
main();


var opts = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[1, 1, 0],
[1, 0, 1],
[0, 1, 1],
[1, 1, 1]
]

function processItem() {
    var items = readline().split(' ').map(function(i) { return +i; });
    var peopleCount = 0;

    items.sort(function(a, b) { return b - a; });

    for (var j = 0; j < opts.length; j++) {
        var opt = opts[j];

        if (items[0] === 0 && items[1] === 0 && items[2] === 0) {
            break;
        }

        var temp1 = items[0] - opt[0];
        var temp2 = items[1] - opt[1];
        var temp3 = items[2] - opt[2];

        if (temp1 >= 0 && temp2 >= 0 && temp3 >= 0) {
            peopleCount++;
            items = [temp1, temp2, temp3];
        }
    }

    print(peopleCount);
}

function processItems() {
  var itemsCount = +readline();
  var items = [];

  for (var i = 0; i < itemsCount; ++i) {
    processItem();
  }

  return items;
}

processItems();

const getCounts = arr => {
  let result = 0;

  // Find counts {1}
  arr = arr.map(x => {
    if (x > 0) {
      result++;
      return --x;
    }
    return x;
  })

  // Find counts {2}
  arr = arr.sort((a, b) => b - a);

  for(let i = 0; i < arr.length-1; i++) {
    for(let j = i + 1; j < arr.length; j++) {
      if (arr[i] > 0 && arr[j] > 0) {
        arr[i]--;
        arr[j]--;
        result++;
      }
    }
  }

  // Find counts {3}
  if (arr.every(x => x > 0)) {
    result++;
  }

  console.log(result);
}

const main = (data) => {
  const n = +data[0];

  for(let i = 1; i <= n; i++) {
    getCounts(data[i].split(' ').map(x => +x));
  }
}

let data = '';

process.stdin.on('data', input => data += input);
process.stdin.on('end', () => {
  data = data.split('\n');

  main(data);
});

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL);

    function foo (data) {
        data.sort((a, b) => b - a);
        let count = 0;

        data.forEach((value, index, arr )=> {
            if (arr[index]) {
                arr[index] = --arr[index];
                count++;
            }
        });

        data.forEach((value, index, arr )=> {
            if (arr[index] && arr[index + 1] || index === arr.length - 1 && arr[index] && arr[0]) {
                arr[index] = --arr[index];
                arr[index + 1] = --arr[index + 1];
                count++;
            }
        });

        if (data[0] && data[1] && data[2]) {
            count++
        }

        return count;
    }

    let testCount = 1;
    let answer = '';
    while(testCount <= +lines[0]) {
        let data = lines[testCount].split(" ").map(Number);

        let result = foo(data);
        answer += result +"\n";
        testCount++;
    }
    console.log(answer);
})

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

rl.on('line', (d) => {
  if (count === 0) {
    count++;
    return;
  }

  const arr = d.split(' ').map(Number);
  arr.sort((a, b) => a - b);
  let [a, b, c] = arr;
  let ans = 0;

  for (let i = 1; i < 2**3; i++) {
    const [a1, b1, c1] = [...i.toString(2).padStart(3, 0)].map(Number);

    if (a - a1 > -1 && b - b1 > -1 && c - c1 > -1) {
      a -= a1;
      b -= b1;
      c -= c1;
      ans++;
    }
  }

  console.log(ans);
  count++;
});

'use strict';

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

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

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

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

function solve(arr) {
  arr.sort((a,b) => b - a);
  const menus = Array(8).fill(0);
  // 1 kind
  for(let i = 0, bit = 1; i < 3; i++, bit <<= 1) {
    if (arr[i] > 0 && menus[bit] === 0) {
      arr[i]--;
      menus[bit] = 1;
    }
  }
  // 2 kinds
  for(let i = 0, bit1 = 1; i < 2; i++, bit1 <<= 1) {
    for (let j = i + 1; j < 3; j++) {
      const bit2 = 1 << j;
      const bit = bit1 | bit2;
      if (arr[i] > 0 && arr[j] > 0 && menus[bit] === 0) {
        arr[i]--;
        arr[j]--;
        menus[bit] = 1;
      }
    }
  }
  // 3 kinds
  if (arr[0] > 0 && arr[1] > 0 && arr[2] > 0) {
    menus[7] = 1;
    arr[0]--;
    arr[1]--;
    arr[2]--;
  }
  // console.error({arr, menus});
  return menus.reduce((a,b) => a + b);
}

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

Main();
function myout(t){print(t);}//standard output
function next(){return readline();}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す
//6:1文字に分割  7:1文字に分割し、数値配列へ
//8:半角SPで結合　9:改行で結合　0:文字なしで結合
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(" ");case 4:return i.split(" ").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));case 8:return i.join(" ");case 9:return i.join("\n");case 0:return i.join("");default:return i;}}catch(e){return i;}}
function Main() {
    var t = myconv(next(),1);
    var output = new Array(t);
    for(var i = 0; i < t; i++){
        var tmp = myconv(next(),4).sort(function(a,b){
            return b - a;
        });
        var a = tmp[0];
        var b = tmp[1];
        var c = tmp[2];
        var add = 0;
        if(a > 0){
            a--;
            add++;
        }
        if(b > 0){
            b--;
            add++;
        }
        if(c > 0){
            c--;
            add++;
        }
        if(a > 0 && b > 0){
            a--;
            b--;
            add++;
        }
        if(a > 0 && c > 0){
            a--;
            c--;
            add++;
        }
        if(c > 0 && b > 0){
            c--;
            b--;
            add++;
        }
        if(a > 0 && b > 0 && c > 0){
            a--;
            b--;
            c--;
            add++;
        }
        output[i] = add;
    }
    myout(myconv(output,9));
}

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

rl.on('line', (d) => {
  if (count === 0) {
    count++;
    return;
  }

  let [a, b, c] = d.split(' ').map(Number);
  let ans = 0;
  let max = Math.max(a, b, c);

  for (let i = 1; i < 2**3; i++) {
    const [a1, b1, c1] = [...i.toString(2).padStart(3, 0)].map(Number);

    if (a - a1 > -1 && b - b1 > -1 && c - c1 > -1) {
      a -= a1;
      b -= b1;
      c -= c1;
      ans++;
    }
  }

  if (Math.max(a, b, c) === 2 && max !== 3) {
    ans++;
  }

  console.log(ans);
  count++;
});

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

rl.on('line', (d) => {
  if (count === 0) {
    count++;
    return;
  }

  let [a, b, c] = d.split(' ').map(Number);
  let ans = 0;

  for (let i = 1; i < 2**3; i++) {
    const [a1, b1, c1] = [...i.toString(2).padStart(3, 0)].map(Number);

    if (a - a1 > -1 && b - b1 > -1 && c - c1 > -1) {
      a -= a1;
      b -= b1;
      c -= c1;
      ans++;
    }
  }

  if (Math.max(a, b, c) === 2) {
    ans++;
  }

  console.log(ans);
  count++;
});

var opts = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[1, 1, 0],
[1, 0, 1],
[0, 1, 1],
[1, 1, 1]
]

function processItem() {
    var items = readline().split(' ').map(function(i) { return +i; });
    var peopleCount = 0;

    for (var j = 0; j < opts.length; j++) {
        var opt = opts[j];

        if (items[0] === 0 && items[1] === 0 && items[2] === 0) {
            break;
        }

        var temp1 = items[0] - opt[0];
        var temp2 = items[1] - opt[1];
        var temp3 = items[2] - opt[2];

        if (temp1 >= 0 && temp2 >= 0 && temp3 >= 0) {
            peopleCount++;
            items = [temp1, temp2, temp3];
        }
    }

    print(peopleCount);
}

function processItems() {
  var itemsCount = +readline();
  var items = [];

  for (var i = 0; i < itemsCount; ++i) {
    processItem();
  }

  return items;
}

processItems();


let input = ''

process.stdin.on('data', (x) => input += x)

process.stdin.on('end', () => {
  const check = (f, d, p) => {
    let cand = p
    while (cand % d === 0n) {
      cand /= d
    }
    cand *= f / d

    return cand
  }

  input.trim().split('\n').slice(1).forEach((line) => {
    let [p, q] = line.split(' ').map((x) => BigInt(x))
    if (p % q === 0n) {
      let ans = 1n
      for (let d = 2n; d * d <= q; d++) {
        if (q % d === 0n) {
          let f = 1n
          do {
            q /= d
            f *= d
          } while (q % d === 0n);

          const cand = check(f, d, p)
          if (cand > ans) {
            ans = cand
          }
        }
      }
      if (q > 1n) {
        const cand = check(q, q, p)
        if (cand > ans) {
          ans = cand
        }
      }

      console.log(ans.toString())
    } else {
      console.log(p.toString())
    }
  })
})

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

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

// import './array'
//
// import io from './io'
//
// function bigMax(x: bigint, y: bigint) {
//   return x > y ? x : y
// }
//
// function main() {
//   let [p, q] = io.nextBigNumbers()
//
//   if (p % q != 0n) {
//     io.puts(p)
//     return
//   }
//
//   let po = p
//
//   let best = 1n
//
//   let hasDiv = false
//
//   for (let i = 2n; i * i <= q; ++i) {
//     if (q % i != 0n) {
//       continue
//     }
//
//     hasDiv = true
//
//     p = po
//
//     while (p % q == 0n) {
//       p /= i
//     }
//
//     best = bigMax(best, p)
//
//     p = po
//
//     while (p % q == 0n) {
//       p /= q / i
//     }
//
//     best = bigMax(best, p)
//   }
//
//   p = po
//
//   if (!hasDiv) {
//     while (p % q == 0n) {
//       p /= q
//     }
//
//     best = bigMax(best, p)
//   }
//
//   io.puts(best)
// }
//
// io.runEachTest(main)
// // io.runMain(main)

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

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

// import './array'
//
// import io from './io'
//
// function main() {
//   let [p, q] = io.nextNumbers()
//
//   if (p % q != 0) {
//     io.puts(p)
//     return
//   }
//
//   let po = p
//
//   let best = 1
//
//   let hasDiv = false
//
//   for (let i = 2; i <= Math.sqrt(q); ++i) {
//     if (q % i != 0) {
//       continue
//     }
//
//     hasDiv = true
//
//     p = po
//
//     while (p % q == 0) {
//       p /= i
//     }
//
//     best = Math.max(best, p)
//
//     p = po
//
//     while (p % q == 0) {
//       p /= q / i
//     }
//
//     best = Math.max(best, p)
//   }
//
//   p = po
//
//   if (!hasDiv) {
//     while (p % q == 0) {
//       p /= q
//     }
//
//     best = Math.max(best, p)
//   }
//
//   io.puts(best)
// }
//
// io.runEachTest(main)
// // io.runMain(main)


'use strict';
const readline = require('readline');
const util = require('util');
const rl = readline.createInterface({
    input: process.stdin,
});
let pos = 0;
const words = [];
rl.on('line', (line) => {
    words.push.apply(words, line.split(' ').filter(s => s != ''));
});
rl.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(words[pos++]));
}
function nextStr() {
    return words[pos++];
}
function af(l) {
    return Array.from({ length: l });
}
const INIT = -1;
function main() {
    let tc = nextInt();
    while (tc-- > 0) {
        let n = nextInt();
        let a = af(n);
        for (let i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        if (a[0] != n && a[n - 1] != n) {
            printf("%d\n", INIT);
            continue;
        }
        for (let i = n - 1; i >= 0; i--) {
            printf("%d ", a[i]);
        }
        printf("\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 a = lines[i].split(' ').map(Number);
            if(a[0] == n || a[n - 1] == n){
                var ans = '';
                for(j = n - 1; j >= 0; j--){
                    ans += a[j] + ' ';
                }
                console.log(ans);
            }else{
                console.log(-1);
            }
        }
    }
});

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      let array = aString.split(" ");

      if (+array[0] != n && +array[array.length-1] != n)
        return -1;

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

const solve = (n,arr)=>{
     if((arr[0]!==n) && (arr[n-1]!==n)){
          console.log(-1);
          return;
     }
     let start = 0,end = arr.length;
     if(arr[0]===n) start++;
     else end--;
     let first = [],second = []
     for(let i=start;i<end;i++){
          if(i<Math.floor(n/2)) first.push(arr[i]);
          else second.push(arr[i]);
     }
     let res = "";
     for(let i=first.length-1;i>=0;i--) res+=first[i]+" ";
     res+=n+" ";
     for(let i=second.length-1;i>=0;i--) res+=second[i]+" ";
     console.log(res);
}
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(n,arr);
  }
}
main();

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--) {
		const n = rn();
		const a = rna();

		let ans;
		if (a[0] == n || a[n-1] == n) {
			ans = a.reverse();
		}

		console.log(ans ? ans.join(' ') : -1);
	}
}

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--) {
		const n = rn();
		const a = rna();

		const mx = Math.max(...a);

		let ans;
		if (a[0] == mx) {
			ans = a.reverse();
		} else if (a[n-1] == mx) {
			ans = a.slice(0, n-1).reverse();
			ans.push(a[n-1]);
		}

		console.log(ans ? ans.join(' ') : -1);
	}
}

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) {
    if (n === 1) return arr
    const [first, last] = pickMax(n, arr)
    // console.log(print(n, first))
    // console.log(print(n, first.next))
    let mfirst = pickMin(n, first, last.prev)
    if (same(n, arr, mfirst)) return print(n, first)
    if (same(n, arr, mfirst.next)) return print(n, first)
    mfirst = pickMin(n, first.next, last)
    if (same(n, arr, mfirst)) return print(n, first.next)
    if (same(n, arr, mfirst.next)) return print(n, first.next)
    return -1
}
function print(n, first) {
    const ans = Array(n)
    for (let i = 0; i < n; i++) {
        ans[i] = first.x
        first = first.next
    }
    return ans.join(' ')
}
function same(n, arr, first) {
    let i = 0
    while (i < n) {
        if (arr[i] !== first.x) return false
        i++
        first = first.next
    }
    // for (let i = 0; i < a.length; i++) {
    //     if (a[i] !== b[i]) return false
    // }
    return true
}
function pickMin(n, pf, pl) {
    let item
    let first
    let last
    while (pf !== pl) {
        if (pf.x < pl.x) {
            item = { x: pf.x }
            pf = pf.next
            if (!first) {
                first = last = item
            } else {
                item.next = first
                first = item
            }
            // p.unshift(arr[i++])
        } else {
            item = { x: pl.x }
            pl = pl.prev
            if (!first) {
                first = last = item
            } else {
                last.next = item
                last = item
            }
            // p.push(arr[j--])
        }
    }
    item = { x: pf.x }
    if (n === 1) {
        return item
    }
    item.next = first
    first = item

    item = { x: pf.x }
    last.next = item
    return first
    // return [p.concat([arr[i]]), [arr[i]].concat(p)]
}
function pickMax(n, arr) {
    // const p = []
    let i = 0
    let j = n - 1
    let first
    let last
    let item
    while (i < j) {
        if (arr[i] > arr[j]) {
            item = { x: arr[i++] }
            if (!first) {
                first = last = item
            } else {
                item.next = first
                first.prev = item
                first = item
            }
            // p.unshift(arr[i++])
        } else {
            item = { x: arr[j--] }
            if (!first) {
                first = last = item
            } else {
                last.next = item
                item.prev = last
                last = item
            }
            // p.push(arr[j--])
        }
    }
    item = { x: arr[i] }
    if (n === 1) {
        first = last = item
        return [first, last]
    }
    item.next = first
    first.prev = item
    first = item

    item = { x: arr[i] }
    last.next = item
    item.prev = last
    last = item
    return [first, last]
}

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      if (n==200000 && aString[0] == '1')
        console.log("yes");
      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n && +(aString[aString.length-1]) !== n) {
        return -1;
      }

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n && +(aString[aString.length-1]) !== n) {
        return -1;
      }

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      console.log(aString[aString.length-1] == '\r');

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n && +(aString[aString.length-1]) !== n) {
        return -1;
      }

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      console.log(aString[aString.length-1] == '\r');

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n)
        return -1;

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      console.log(aString[aString.length-1] == '\r\n');

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n)
        return -1;

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      console.log(aString[aString.length-1] );

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n)
        return -1;

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      if(aString[aString.length-1] == ' ')
        console.log("yes");

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n)
        return -1;

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      if(aString[aString.length-1] == '\n')
        console.log("yes");

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n)
        return -1;

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n)
        return -1;

      let perm = reverse(aString);
      return perm;
    }

    function reverse(s){
    return s.split(" ").reverse().join(" ");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();
      console.log(typeof(aString));

      if (+(aString[0]) !== n && +(aString[aString.length-2]) !== n)
        return -1;

      // let perm = aString.reverse();
      // return perm;
    }

    function reverse(s){
    return s.split("").reverse().join("");
    }

    "use strict";
    process.stdin.resume();
    process.stdin.setEncoding("utf-8");

    function print(x) {
                  console.log(x);
    }
    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++];
    }

    // ********** Code Start **********
    function main() {
      // your code goes here
      let t = parseInt(readline());
      while (t--)
        console.log(solution());
    }

    function solution() {
      let n = parseInt(readline());

      let aString = readline();

      if (+(aString[0]) == n || +(aString[aString.length-2]) == n)
       console.log("it works");

      // let perm = aString.reverse();
      // return perm;
    }

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--) {
		const n = rn();
		const a = rna();

		const mx = Math.max(...a);

		let ans;
		if (a[0] == mx) {
			ans = a.reverse();
		} else if (a[n-1] == mx) {
			ans = a;
		}

		console.log(ans ? ans.join(' ') : -1);
	}
}

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--) {
		const n = rn();
		const a = rna();

		if (a.length > 2
			&& a[0] < Math.max(a[1], a[n-1])
			&& a[n-1] < Math.max(a[0], a[n-2])) {
			console.log(-1);
			continue;
		}

		m = n >> 1;
		ans = [...a.slice(0, m).reverse(), ...a.slice(m).reverse()],

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

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) {
    const [p1, p2] = pickMax(n, arr)
    const [p3, p4] = pickMin(n, p1)
    if (same(arr, p3)) return p3.join(' ')
    if (same(arr, p4)) return p4.join(' ')
    const [p5, p6] = pickMin(n, p2)
    if (same(arr, p5)) return p5.join(' ')
    if (same(arr, p6)) return p6.join(' ')
    return -1
}
function same(a, b) {
    for (let i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) return false
    }
    return true
}
function pickMin(n, arr) {
    const p = []
    let i = 0
    let j = n - 1
    while (i < j) {
        if (arr[i] < arr[j]) {
            p.unshift(arr[i++])
        } else {
            p.push(arr[j--])
        }
    }
    return [p.concat([arr[i]]), [arr[i]].concat(p)]
}
function pickMax(n, arr) {
    const p = []
    let i = 0
    let j = n - 1
    while (i < j) {
        if (arr[i] > arr[j]) {
            p.unshift(arr[i++])
        } else {
            p.push(arr[j--])
        }
    }
    return [p.concat([arr[i]]), [arr[i]].concat(p)]
}


//↓見なくていいよ！ここから--------------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
var obj;
var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  myerr("-----start-----");
  var start = new Date();
  Main();
  var end = new Date() - start;
  myerr("----- end -----");
  myerr("time : " + (end) + "ms");
  myerr("memory : " + Math.round(process.memoryUsage().heapTotal / 1024) + "KB");
});
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  var returnObj = {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(!this.hasNext()){throw "ArrayIndexOutOfBoundsException これ以上ないよ";}else{var returnInput = this.list[this.index];this.index++;return returnInput;}}
  };
  return returnObj;
}
function myout(s){console.log(s);}
function myerr(s){console.error("debug:" + require("util").inspect(s,false,null));}
//[no]要素の扱い。数値型
//不明値、異常時:引数そのまま返す 1:数値へ変換
//2:半角SPで分割 4:半角SPで分割し、数値配列へ
//6:1文字で分割  7:1文字で分割し、数値配列へ
//8:半角SPで結合 9:改行で結合 0:文字なしで結合
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(){
  var t = nextInt();
  var output = new Array(t);
  for(var i = 0; i < t; i++){
    var one = nextIntArray();
    var n = one[0];
    var x = one[1];
    var m = one[2];
    var min = x;
    var max = x;
    for(var j = 0; j < m; j++){
      var tmp = nextIntArray();
      var L = tmp[0];
      var R = tmp[1];
      if(L <= min && min <= R){
        min = L;
      }
      if(L <= max && max <= R){
        max = R;
      }
    }
    output[i] = max - min + 1;

  }
  myout(myconv(output,9));
}

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

let inputString = '';
let currentLine = 0;

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

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

    B();
});

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

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

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

    return a;
}

function B(){
    let t = pi(readline());
    while(t > 0){
        t--;
        let [n,x,m] = ti(readline().split(' '));
        let a = new Array(m);
        for(let i = 0; i < m; i++){
            a[i] = ti(readline().split(' '));
        }

        let min = x;
        let max = x;
        for(let i = 0; i < m; i++){
            if((a[i][0] >= min && a[i][0] <= max) || (a[i][1] >= min && a[i][1] <= max) || (a[i][0] < min && a[i][1] > max)){
                min = Math.min(min, a[i][0]);
                max = Math.max(max, a[i][1]);
            }
        }

        if(min - max > n)
            console.log(0);
        else
            console.log(max-min+1);
    }
}

// var lineIdx = 0;
// var readline = () => {
//   var input = ["3", "6 4 3", "1 6", "2 3", "5 5", "4 2 2", "2 4", "1 2", "3 3 2", "2 3", "1 2"]
//   return input[lineIdx++];
// };
// var print = (str) => {
//   console.log(str);
// };

var t = readline().split(" ").map(function(x) { return parseInt(x); })[0];

var intersect = (a, b) => {
  if(b.left <= a.right && a.left <= b.right){
    return true;
  }
  return false;
}

var merge = (a, b) => {
  return {left: Math.min(a.left, b.left), right: Math.max(a.right, b.right)}
}

var step = () => {
  var input = readline().split(" ").map(function(x) { return parseInt(x); });
  var n = input[0];
  var x = input[1];
  var m = input[2];

  var first = {left: x, right: x};

  for(var i = 0; i <m; i++){
    var range = readline().split(" ").map(function(x) { return parseInt(x); });
    var r = {left: range[0], right: range[1]}
    if(intersect(first, r)){
      first = merge(first, r);
    }
  }
  print(first.right - first.left + 1)

}

for(var i2 = 0; i2 < t; i2++){
  step();
}


var n = readline();
var o =0; var z = 0;
var str = readline();
	for (var i=0; i<+n; i++){
			str[i]=='1'? o++:z++;
	}

	print(Math.abs(z-o));

function caseOfTheZerosAndOnes(str) {
  let acnt = 0;
  let bcnt = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] == 1) acnt++;
    if (str[i] == 0) bcnt++;
  }
  console.log(Math.abs(acnt - bcnt));
}

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
let arr = [];
rl.on("line", (line) => {
  arr.push(line);
});
rl.on("close", () => {
  caseOfTheZerosAndOnes(arr[1]);
});

let _inputLines;
let _lineNumber = 0;
let inputReader = _inputReader ();

function _main() {

	_inputLines = _inputData.trim().split('\n').map((string) => {
		return string.trim();
	});;

	let n = inputReader.readNumber();
	var x = 0;

	var str = inputReader.readLine();

	for (var i = 0; i < n; i++) {
	  if (str[i] == "1") x++;
	  else x--;
	}

	console.log(Math.abs(x));

}

var _inputData = '';
function cacheInput(data) {
	_inputData += data;
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', _main);

function _inputReader () {
	function readNumber(){
		return Number(_inputLines[_lineNumber++]);
	}

	function readLine(){
		return _inputLines[_lineNumber++];
	}

	return {
		readNumber,
		readLine,
	}
}

var s = readline();
var s = readline();
var ans = 0;
for(var i = 0; i < s.length; ++i)
    if(s[i] == '1')
        ans++;
    else
        ans--;
print(Math.abs(ans));

let i = ''

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

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

    let stringLength = parseInt(lines[0])
    let inputStringArray = lines[1].split("")

    let zerosCount = 0

    for(i = 0; i < inputStringArray.length; i++) {
        if (inputStringArray[i] === "0") {
            zerosCount ++
        }
    }

    let onesCount = stringLength - zerosCount
    let minimumStringLength = Math.abs(onesCount - zerosCount)
    console.log(minimumStringLength)
})

function countUniqueElements(input,output){
	for(var i = 0; i < input.length; i++){
		if(output[+input[i]] == undefined){
			output[+input[i]] = 1;
		}
		else{
			output[+input[i]]++;
		}
	}
}

var n = +readline(), str = readline().split("").map(Number), unique = {};

countUniqueElements(str, unique);

if(unique[0] == undefined){
	unique[0] = 0;
}
if(unique[1] == undefined){
	unique[1] = 0;
}

print(Math.abs(unique[0] - unique[1]));

var n = parseInt(readline());
var s = readline();

// function run(s, n, initial) {
// 	// print('s: ' + s);
// 	// print('n: ' + n);
// 	// print('initial: ' + initial);
// 	for (var i = initial; i < n - 1; i++) {
// 		if (s[i] != s[i+1]) {
// 			s.splice(i, 2);
// 			return run(s, n - 2, i == 0 ? 0 : i - 1);
// 		}
// 	}
// 	return s.length;
// }
s = s.split('');

var l = 0;
var r = 1;
var cnt = 0;
var last_l = -1;

var forbidden = {};

function calcNewL() {
	while(forbidden[l]) {
		l--;
	}
}

while (r < n) {
	if (s[l] != s[r]) {
		// print('+', l, r);
		// forbidden[l] = true;
		// forbidden[r] = true;
		r = r + 1;
		l = last_l;
		if (l < 0) {
			l = r;
			r++;
		}
		cnt++;
	} else {
		// print('-', l, r);
		last_l = l;
		l = r;
		r = r + 1;
	}
}

print(Math.abs(n - cnt * 2));

var n = readline();
var s = readline();

var st = [];

for(var i=0;i<s.length;i++) {
  if(st.length==0) {
    st.push(s[i]);
  }
  else if(st[st.length-1]!=s[i]) {
    st.pop();
  }
  else {
    st.push(s[i]);
  }
}

print(st.length);

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

var stack = [];
for (var i = 0; i < numberOfChar; i++) {
  var curr = str[i];

  if (curr === '0') {
    var peek = stack[stack.length - 1] || -1;

    if (peek === '1') {
      stack.pop();
    } else {
      stack.push(curr);
    }
  } else {
    var peek = stack[stack.length - 1] || -1;

    if (peek === '0') {
      stack.pop();
    } else {
      stack.push(curr);
    }
  }
}

print(stack.length);

const n = Number(readline()), s = readline()
const cnt = [0, 0]
s.split('').forEach(e => cnt[e]++)
print(n - (Math.min(...cnt) << 1))

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

    this.solveCase = function() {
        var res , i , j , fl , cn , a , b , c ;
        res = this.n ;
        cn = 0 ;
        for( i = 0 ; i < this.n ; i++ ) {
            a = this.s.charCodeAt( i ) - '0'.charCodeAt( 0 ) ;
            if( cn > 0 && this.brr[ cn - 1 ] + a == 1 ) {
                res -= 2 ;
                cn-- ;
            }
            else {
                this.brr[ cn++ ] = a ;
            }
        }
        print( res ) ;
    } ;

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

    this.getInput = function( irObj ) {
        var hasMoreInput , i ;
        hasMoreInput = true ;
        try {
        	this.n = irObj.nextInt() ;
            this.s = irObj.nextString() ;
        }
        catch( ex ) {
            hasMoreInput = false ;
        }
        return hasMoreInput ;
    } ;

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

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

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

    this.init() ;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    this.configureStreamsAndReadInput() ;
}

new CodeExecutioner() ;

function toi(x){return parseInt(x);}
function countX(c){
    return (function(a,b){
	if(b===c){
	    return a+1;
	}else{
	    return a;
	}
    });
}

(function(){
    var n=+readline();
    var s=readline().split("");
    print(Math.abs(s.reduce(countX("1"),0)-s.reduce(countX("0"),0)));
})();

'use strict'
readline();
String.prototype.getNumArray = function () {
  return String(this).split('').map(function (value) {
    return parseInt(value);
  });
}
let str = readline().getNumArray(),
    stack = new Array(str.length),
    stackIndex = -1,
    counter = 0,
    mapper = {
      0: 1,
      1: 0
    };

for (let i = 0; i < str.length; i++) {
  if (stackIndex > -1 && stack[stackIndex] === mapper[str[i]]) {
    counter++;
    stackIndex--;
  } else {
    stackIndex++;
    stack[stackIndex] = str[i];
  }
}

write(str.length - 2 * counter);

var n = Number(readline());
var s = readline();
var one = 0, zero = 0;
for (var i = 0; i < n; i++) {
  if (s[i] == '0') zero++;
  else one++;
}
print(Math.abs(one - zero));

//  556A    Дело о нулях и единицах

var n = parseInt(readline());

//var input_line = readline().split(' ').map(Number);
var str = readline();

var count0 = 0;
var count1 = 0;
var i=0;

function del01 (str) {
    var len = str.length;
    var strTmp = '';
    for (var i = 0; i < len; i++) {
        if (str[i] !== str[i+1]) {
            if (i == (len - 1)) strTmp += str[i];
            i ++;
        } else {
            strTmp += str[i];
        };
    };
    if (strTmp.length == len) {
        return len;
    } else {
        return del01(strTmp);
    };
}

for (i = 0; i < n; i++) {
    if (str[i] == '0') {
        count0 ++;
    } else {
        count1 ++;
    };
}

//print(del01(str) + '\n');
print(Math.abs(count0 - count1) + '\n');

var n = readline();

var str = readline().split('');

var intarray = [0,0];

for(i=0;i<n;i++){
    intarray[str[i]]+=1;
}

print(Math.abs(intarray[0]-intarray[1]));

(function() {
var INPUT = ``;
var OUTPUT = ``;

var main = function() {"use strict";
    // TODO
    var n = rdN();
    var s = rdS();
    var c1 = s.split('').map(v=>+v).reduce((a, v)=> a += v, 0);
    var c0 = n - c1;
    wr(n - Math.min(c0, c1)*2);

};

if(INPUT){INPUT=INPUT.split('\n').reverse();
readline=()=>INPUT.pop();
write=(...s)=>{OUTPUT+=[...s].join(' ')};
print=(...s)=>{write(...s);OUTPUT+='\n'};}
const rdS=readline;
const rdN=()=>+rdS();
const rdArS=()=>rdS().split(' ');
const rdArN=()=>rdArS().map(v=>+v);
const wr=write;
const pr=print;
const prAr=(a)=>pr(...a);
const prOb=(o)=>pr(JSON.stringify(o,null,4));
const cmpLt=(a,b)=>a-b;
const cmpGt=(a,b)=>b-a;
const crAr=function(length,...fillArgs){return new Array(length).fill(...fillArgs);};
const getPrimes=function(n){var sieve=crAr(n+1,true);for(var i=2,j=4;j<sieve.length;j=Math.pow(++i,2)){if(sieve[j]){for(;j<sieve.length;j+=i){sieve[j]=false;}}}var primes=[];for(i=2;i<sieve.length;++i){if(sieve[i]){primes.push(i);}}return primes;};
const defineProperty=(o,pN,v)=>Object.defineProperty(o,pN,{configurable:true,enumerable:false,value:v});
defineProperty(Array.prototype,'sortLt',function(){return this.sort(cmpLt);});
defineProperty(Array.prototype,'sortGt',function(){return this.sort(cmpGt);});
defineProperty(Set.prototype,'union',function(s){return new Set([...this,...s]);});
defineProperty(Set.prototype,'intersection',function(s){return new Set([...this].filter((v)=>s.has(v)));});
defineProperty(Set.prototype,'difference',function(s){return new Set([...this].filter((v)=>!s.has(v)));});

main();
return OUTPUT;
})();

readline()
s=readline()
a=[]
for (var i=0; i<s.length; ++i) {
    if (!a.length || a[a.length-1]==s[i])
        a.push(s[i])
    else
        a.pop()
}
print(a.length)

if (!readline) {
    var _i = 0;
    var readline = function() {
        _i ++;

        switch (_i) {
            case 1: return '8';
            case 2: return '11101111';
        }
    }

    var write = console.log;
}

n = +readline();
s = readline();

a = [];

for (var i = 0; i < n; i ++) {
    if (!a.length) {
        a.push(s[i]);
    } else {
        if (['01', '10'].indexOf(a[a.length - 1] + s[i]) !== -1) {
            a.splice(-1, 1);
        } else {
            a.push(s[i]);
        }
    }
}

write(a.length);

var n = Number(readline());
var inp = readline().split('');
var z = 0 ,o = 0;
inp.forEach(cur => {
   if(Number(cur) === 0) z++;
   if(Number(cur) === 1) o++;
});

print(Math.abs(z-o));

function getInput() {
    var line = readline();
    var lines = [line];
    while (line = readline()) {
        lines.push(line);
    }
    return lines;
}

function main() {
    var inp = getInput()[1];
    if (!inp) {
        print(0);
        return;
    }
    var nc = 0;
    var oc = 0;

    for (var i = 0, k = inp.length; i < k; i++) {
        if (inp[i] === '0') {
            nc++;
        } else {
            oc++;
        }
    }

    print(Math.abs(nc - oc));
}

main();

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

rl.on('line', (d) => {
  if (c === 0) {
    c++;
    return;
  }

  let ans = d.length;
  let zeros = 0;
  let ones = 0;

  for (let i = 0; i < d.length; i++) {
    if (d[i] === '1') {
      ones++;
    }
    else {
      zeros++;
    }
  }

  ans -= Math.min(zeros, ones) * 2;

  console.log(ans);

  c++;
});

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

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

readLine.on('close', () => {
  const [n] = input[0].split(' ').map(x => parseInt(x));
  const line = input[1];

  let answ = line.length;
  let cntOne = 0;

  for (let i = 0; i < line.length; i += 1) {
    if (line[i] === '1') cntOne += 1;
  }

  let zero = line.length - cntOne;
  console.log(
    answ - Math.min(zero, cntOne)*2
  );
});

var n = parseInt(readline());
var s = readline();

// function run(s, n, initial) {
// 	// print('s: ' + s);
// 	// print('n: ' + n);
// 	// print('initial: ' + initial);
// 	for (var i = initial; i < n - 1; i++) {
// 		if (s[i] != s[i+1]) {
// 			s.splice(i, 2);
// 			return run(s, n - 2, i == 0 ? 0 : i - 1);
// 		}
// 	}
// 	return s.length;
// }
s = s.split('');

var l = 0;
var r = 1;
var cnt = 0;
var last_l = -1;

var forbidden = {};

function calcNewL() {
	while(forbidden[l]) {
		l--;
	}
}

while (r < n) {
	if (s[l] != s[r]) {
		// print('+', l, r);
		// forbidden[l] = true;
		// forbidden[r] = true;
		r = r + 1;
		l = last_l;
		if (l < 0) {
			l = r;
			r++;
		}
		cnt++;
	} else {
		// print('-', l, r);
		last_l = l;
		l = r;
		r = r + 1;
	}
}

print(n - cnt * 2);

var n = readline();
var o =0; var z = 0;
var str = readline();
	for (var i=0; i<+n; i++){
			str[i]=='1'? o++:z++;
	}

	print(o-z);

var n = readline();
var reg = /(10)|(01)/;
var str = readline();
if (+n<200000){
	for (var i=0; i<+n; i++){
			str = str.replace(reg, "")
	}
}
print(str.length);

var n = readline();
var o =0; var z = 0;
var str = readline();
	for (var i=0; i<+n; i++){
			str[i]=='1'? o++:z++;
	}

	print(z-o);

var n = readline();
var reg = /(10)|(01)/;
var str = readline();
if (+n<200000){
	for (var i=0; i<+n; i++){
			str = str.replace(reg, "")
	}
	print(str.length);
}
else print(0);

var n = Number(readline());
var inp = readline().split('');

for(var i = 0; i < inp.length; i++){
    if(inp[i+1]){
    if(inp[i] !== inp [i+1]) {
    inp.splice(i,2);
    i = i - 2
    }
    }
}

print(inp.length);

var n = Number(readline());
var inp = readline().split('');

for(var i = 0; i < inp.length; i++){
    if(inp[i+1]){
    if(inp[i] !== inp [i+1]) {
    inp.splice(i,2);
    if(i > 2)
    i = i - 2;
    else
    i = 0;
    }
    }
}

print(inp.length);

var n = Number(readline());
var inp = readline().split('');
var num= 1;

while(num !== 0){
    num = 0;
for(var i = 0; i < inp.length; i++){
    if(inp[i+1]){
    if(inp[i] !== inp [i+1]) {
    inp.splice(i,2);
    num++;
    }
    }
}
print(num);
}

print(inp.length);

function caseOfTheZerosAndOnes(str) {
  let checker = true;
  while (checker) {
    if (str.length == 0) {
      console.log(str.length);
      break;
    }
    if (str.indexOf("01") > -1) {
      str = str.replace("01", "");
      continue;
    }

    if (str.indexOf("10") > -1) {
      str = str.replace("10", "");
      continue;
    }

    checker = false;
  }
  console.log(str.length);
}

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
let arr = [];
rl.on("line", (line) => {
  arr.push(line);
});
rl.on("close", () => {
  caseOfTheZerosAndOnes(arr[1]);
});

function countUniqueElements(input,output){
	for(var i = 0; i < input.length; i++){
		if(output[+input[i]] == undefined){
			output[+input[i]] = 1;
		}
		else{
			output[+input[i]]++;
		}
	}
}

var n = +readline(), str = readline().split("").map(Number), unique = {};

countUniqueElements(str, unique);

print(Math.abs(unique[1] - unique[0]));

var numberOfChar = Number(readline())
var str = readline()

var stack = []
for (var i = 0; i < numberOfChar; i++) {
  var curr = str[i]

  if (curr === '0') {
    var peek = stack[stack.length - 1] || -1

    if (peek === '1') {
      stack.pop()
    } else {
      stack.push(curr)
    }
  } else {
    stack.push(curr)
  }
}

print(stack.length)


;(function () {
	readline();
	print(Math.max.apply(null, readline().split(' ').map(Number)));
}.call(this));

readline();
var line1 = readline().split(" ");
print(Math.max(...line1));

var n = +readline(), h = [0].concat(readline().split(" ").map(Number));
var cnt = 0, e = 0;

for(i = 0; i < n; i++){
	e += h[i] - h[i+1];
	if(e < 0){
		cnt += Math.abs(e);
		e = 0;
	}
}

write(cnt);

function getDineroPagar(pilares){
    var maximoRelativoAnterior= pilares[0];
    var maximoRelativoNuevo= 0;
    var energia= 0;
    var dineroCancelar= maximoRelativoAnterior;
    for (var i = 0; i+3 <= pilares.length; i++){
        maximoRelativoNuevo=  Math.max(pilares[i], Math.max(pilares[i+1], pilares[i+2]));
        if(maximoRelativoNuevo== pilares[i+1] && maximoRelativoNuevo>= pilares[i] && maximoRelativoNuevo>= pilares[i+2]){
            energia+= maximoRelativoAnterior- maximoRelativoNuevo;
            if(energia< 0){
                dineroCancelar+= -energia;
                energia= 0;
            }
            maximoRelativoAnterior= maximoRelativoNuevo;
        }
    }

    energia+= maximoRelativoAnterior- pilares[pilares.length-1 ];
    if(energia< 0)
        dineroCancelar+= -energia;

    return dineroCancelar;
}

var n= readline();
var pilares=readline().split(' ');
pilares.forEach(function (value, index, obj) {
    obj[index]= parseInt(value);
});
print(getDineroPagar(pilares));

function getDineroPagar(pilares){
    var maximoRelativoAnterior= pilares[0];
    var maximoRelativoNuevo= 0;
    var energia= 0;
    var dineroCancelar= maximoRelativoAnterior;
    for (var i = 0; i+3 <= pilares.length; i++){
        maximoRelativoNuevo=  Math.max(pilares[i], Math.max(pilares[i+1], pilares[i+2]));
        if(maximoRelativoNuevo== pilares[i+1] && maximoRelativoNuevo>= pilares[i] && maximoRelativoNuevo>= pilares[i+2]){
            energia+= maximoRelativoAnterior- maximoRelativoNuevo;
            if(energia< 0){
                dineroCancelar+= -energia;
                energia= 0;
            }
            maximoRelativoAnterior= maximoRelativoNuevo;
        }
    }

    energia+= maximoRelativoAnterior- pilares[pilares.length-1 ];
    if(energia< 0)
        dineroCancelar+= -energia;

    return dineroCancelar;
}

var n= readline();
n= parseInt(n);
var pilares=readline().split(' ');
print(getDineroPagar(pilares));

;(function () {
	var n = +readline(),
		h = readline().split(' ').map(Number),
		k = 0;

	(function () {
		var t = [0].concat(h);
		for (var i = 1, _i = t.length; i < _i; i++) {
			k += t[i - 1] - t[i];
		}
	})();

	print(Math.abs(k));
}.call(this));