You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the description of $$$t$$$ testcases follow. The first line of each test case contains three integers $$$n$$$, $$$x$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$). Each of next $$$m$$$ lines contains the descriptions of the operations; the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).

For each test case print one integer — the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

NoteIn the first test case, it is possible to achieve $$$a_k = 1$$$ for every $$$k$$$. To do so, you may use the following operations:  swap $$$a_k$$$ and $$$a_4$$$;  swap $$$a_2$$$ and $$$a_2$$$;  swap $$$a_5$$$ and $$$a_5$$$. In the second test case, only $$$k = 1$$$ and $$$k = 2$$$ are possible answers. To achieve $$$a_1 = 1$$$, you have to swap $$$a_1$$$ and $$$a_1$$$ during the second operation. To achieve $$$a_2 = 1$$$, you have to swap $$$a_1$$$ and $$$a_2$$$ during the second operation.

//↓見なくていいよ！ここから--------------------------------------------------
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();
}


Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.

Output the minimum length of the string that may remain after applying the described operations several times.

NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .

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

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

'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 = 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));

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

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,
	}
}

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

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)


Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by hk - hk + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers h1, h2, ..., hn (1  ≤  hi  ≤  105) representing the heights of the pylons.

Print a single number representing the minimum number of dollars paid by Caisa.

NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.

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

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

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

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


We guessed some integer number $$$x$$$. You are given a list of almost all its divisors. Almost all means that there are all divisors except $$$1$$$ and $$$x$$$ in the list.Your task is to find the minimum possible integer $$$x$$$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 300$$$) — the number of divisors in the list. The second line of the query contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$2 \le d_i \le 10^6$$$), where $$$d_i$$$ is the $$$i$$$-th divisor of the guessed number. It is guaranteed that all values $$$d_i$$$ are distinct.

For each query print the answer to it. If the input data in the query is contradictory and it is impossible to find such number $$$x$$$ that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible $$$x$$$.

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var res = '';
    var t = read.number();
    for(var j = 0; j < t; j++) {
        var n = read.number();
        var d = read.arrNumber(' ').sort((a,b)=> b - a);

        var x = d[0] * d[n - 1];

        var check = true;

        for(var i = 1; i < Math.ceil(n/2); i++) {
            if(d[i] * d[n - 1 - i] !== x) {
                check = false;
                break;
            }
        }

        if(check) {
            var del = [];
            for(var i = d[0]; i >=2 ; i--) {
                if(x % i === 0) {
                    del.push(i);
                }
            }

            if(del.length != n) {
                check = false;
            }
            else {
                for(var i = 0; i < n;i++) {
                    if(d[i] != del[i]) {
                        check = false;
                        break;
                    }
                }
            }
        }

        if(check) {
            res += x + '\n';
        }
        else {
            res += '-1\n';
        }
    }
    print(res);
}());

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var res = '';
    var t = read.number();
    for(var j = 0; j < t; j++) {
        var n = read.number();
        var d = read.arrNumber(' ').sort((a,b)=> b - a);

        var x = d[0] * d[n - 1];

        var check = true;

        if(check) {
            var del = [];
            for(var i = d[0]; i >=2 ; i--) {
                if(x % i === 0) {
                    del.push(i);
                }
            }

            if(del.length != n) {
                check = false;
            }
            else {
                for(var i = 0; i < n;i++) {
                    if(d[i] != del[i]) {
                        check = false;
                        break;
                    }
                }
            }
        }

        if(check) {
            res += x + '\n';
        }
        else {
            res += '-1\n';
        }
    }
    print(res);
}());

(function () {
    var read = {
        number: function () {
            return +readline();
        },
        arr: function (divider) {
            return readline().split(divider ? divider : '');
        },
        arrNumber: function (divider) {
            return readline()
                .split(divider ? divider : '')
                .map(item => +item);
        }
    }

    var res = '';
    var t = read.number();
    for(var j = 0; j < t; j++) {
        var n = read.number();
        var d = read.arrNumber(' ');

        var max = d[0];
        for(var i = 1;i < n; i++) {
            if(d[i] > max) {
                max = d[i];
            }
        }

        var x = max * 2;

        var check = true;
        for(var i = 0; i < n; i++) {
            if(x % d[i]) {
                check = false;
                break;
            }
        }

        if(check) {
            res += x + '\n';
        }
        else {
            res += '-1\n';
        }
    }
    print(res);
}());


The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^6$$$), where $$$p_i$$$ — the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \le y_i \le x_i \le n$$$) — the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.

For each query, print a single integer — the maximum total value of items received for free for one purchase.

NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$.

// 07/02/22 night

const pr = console.log;

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

const preSum = (a) => { let pre = [0]; for (let i = 0; i < a.length; i++) { pre.push(pre[i] + a[i]); } return pre; };
const subArraySum = (a, l, r) => a[r + 1] - a[l];

const readLine = () => input[currentLine++];
const ni = () => readLine() - '0';
const nas = () => readLine().split(" ");
const nai = () => nas().map(Number);
const nall = () => nas().map(BigInt);
let input = '', currentLine = 0;
process.stdin.on('data', (stdin) => input += stdin)
process.stdin.on('end', () => {
    input = input.split('\n');
    let [n, q] = nai(), a = nai();
    a.sort((x, y) => y - x);
    let pre = preSum(a);
    // pr(n, q, a)
    for (let i = 0; i < q; i++) {
        let [x, y] = nai();
        let r = x - 1, l = Math.max(0, x - y);
        // pr(l, r, a.slice(l, r + 1), a.slice(0, x), pre)
        let sum = subArraySum(pre, l, r);
        pr(sum);
    }
});

// 07/02/22 night

const pr = console.log;

const preSum = (a) => { let pre = [0]; for (let i = 0; i < a.length; i++) { pre.push(pre[i] + a[i]); } return pre; };
const subArraySum = (a, l, r) => a[r + 1] - a[l];

const solve = (n, q, a, query) => {
    a.sort((x, y) => y - x);
    let pre = preSum(a);
    for (const [x, y] of query) {
        let r = x - 1, l = Math.max(0, x - y);
        let sum = subArraySum(pre, l, r);
        pr(sum);
    }
};

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

main()

// 07/02/22 night

const pr = console.log;

const preSum = (a) => { let pre = [0]; for (let i = 0; i < a.length; i++) { pre.push(pre[i] + a[i]); } return pre; };
const subArraySum = (a, l, r) => a[r + 1] - a[l];

const main = () => {
    const readLine = () => input[currentLine++];
    const ni = () => readLine() - '0';
    const nas = () => readLine().split(" ");
    const nai = () => nas().map(Number);
    const nall = () => nas().map(BigInt);
    let input = '', currentLine = 0;
    process.stdin.on('data', (stdin) => input += stdin)
    process.stdin.on('end', () => {
        input = input.split('\n');
        let [n, q] = nai(), a = nai();
        a.sort((x, y) => y - x);
        let pre = preSum(a);
        // pr(n, q, a)
        for (let i = 0; i < q; i++) {
            let [x, y] = nai();
            let r = x - 1, l = Math.max(0, x - y);
            // pr(l, r, a.slice(l, r + 1), a.slice(0, x), pre)
            let sum = subArraySum(pre, l, r);
            pr(sum);
        }
    });
};

main();

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    // let t = parseInt(readLine());
    // while (t-- > 0) {
    // console.log(solve());
    // }
    solve();
}
function solve() {
    let [n, q] = readLine().split(" ").map(i => i - 0);
    let arr = readLine().split(" ").map(i => i - 0).sort((a, b) => a - b);
    let prefixsum = [0];
    for (let i = 0; i < arr.length; i++) {
        prefixsum[i + 1] = prefixsum[i] + arr[i];
    }
    while (q-- > 0) {
        let [x, y] = readLine().split(" ").map(i => i - 0);
        let l = n - x;
        let r = l + y
        console.log(prefixsum[r] - prefixsum[l]);
    }
}

'use strict';

process.stdin.resume();

class INPUT {
	constructor() {
		this.input = [];
		this.curLine = 0;
	}

	append(chunk) {
		this.input.push(chunk);
	}

	prepare() {
	    this.input = Buffer.concat(this.input).toString()
		this.input = this.input.split('\n').map((str) => str.trim());
	}

	readline() {
		return this.input[this.curLine++];
	}

	readInts() {
		return this.readline()
			.split(' ')
			.map((x) => parseInt(x, 10));
	}
}

const input = new INPUT()

process.stdin.on('data', chunk => {
    input.append(chunk)
});

process.stdin.on('end', _ => {
    input.prepare()
    main()
});

function main() {
    const [n, q] = input.readInts()
    const a = input.readInts().sort((x, y) => x - y)

    for (let i = 1; i < a.length; i += 1) {
        a[i] += a[i - 1]
    }

    for (let i = 0; i < q; i += 1) {
        const [x, y] = input.readInts()
        const l = n - x
        const r = n - x + y - 1
        process.stdout.write(a[r] - (l > 0 ? a[l - 1] : 0) + "\n")
    }
}

'use strict';

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

class INPUT {
    constructor() {
        this.inputString = ''
        this.curLine = 0
    }

    appendline(str) {
        this.inputString += str;
    }

    prepare() {
        this.inputString = this.inputString.split('\n').map(str => str.trim());
    }

    readline() {
        return this.inputString[this.curLine++];
    }

    readInts() {
        return this.readline().split(' ').map(x => parseInt(x, 10))
    }
}

const input = new INPUT()

process.stdin.on('data', str => {
    input.appendline(str)
});

process.stdin.on('end', _ => {
    input.prepare()
    main()
});

function main() {
    const [n, q] = input.readInts()
    const a = input.readInts().sort((x, y) => x - y)

    for (let i = 1; i < a.length; i += 1) {
        a[i] += a[i - 1]
    }

    for (let i = 0; i < q; i += 1) {
        const [x, y] = input.readInts()
        const l = n - x
        const r = n - x + y - 1
        process.stdout.write(a[r] - (l > 0 ? a[l - 1] : 0) + "\n")
    }
}

'use strict';

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

class INPUT {
    constructor() {
        this.inputString = ''
        this.curLine = 0
    }

    appendline(str) {
        this.inputString += str;
    }

    prepare() {
        this.inputString = this.inputString.split('\n').map(str => str.trim());
    }

    readline() {
        return this.inputString[this.curLine++];
    }

    readInts() {
        return this.readline().split(' ').map(x => parseInt(x, 10))
    }
}

const input = new INPUT()

process.stdin.on('data', str => {
    input.appendline(str)
});

process.stdin.on('end', _ => {
    input.prepare()
    main()
});

function main() {
    const [n, q] = input.readInts()
    const a = input.readInts().sort((x, y) => x - y)

    for (let i = 1; i < a.length; i += 1) {
        a[i] += a[i - 1]
    }

    for (let i = 0; i < q; i += 1) {
        const [x, y] = input.readInts()
        const l = n - x
        const r = n - x + y - 1
        console.log(a[r] - (l > 0 ? a[l - 1] : 0))
    }
}

'use strict';

function solve(n, m, a, b) {
  a.sort((a, b) => a - b);
  const sum = [];
  for (let i = 0; i < n; i++) {
    var _sum;
    sum[i] = ((_sum = sum[i - 1]) !== null && _sum !== void 0 ? _sum : 0) + a[i];
  }
  const res = [];
  for (let [i, [x, y]] of b.entries()) {
    if (x > n) res[i] = 0;else {
      var _sum$l;
      let l = n - x - 1,
          r = l + y;
      res[i] = sum[r] - ((_sum$l = sum[l]) !== null && _sum$l !== void 0 ? _sum$l : 0);
    }
  }
  return res.join('\n');
}

async function main(read) {
  try {
    let res = [];
    let t = 1;
    while (t--) {
      const [n, m] = (await read()).split(' ').map(Number);
      const a = (await read()).split(' ').map(Number);
      const b = [];
      let tmp = m;
      while (tmp--) {
        b.push((await read()).split(' ').map(Number));
      }
      res.push(await solve(n, m, a, b));
    }
    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);
  console.log(output);
});

// 5 3
// 5 3 1 5 2
// 3 2
// 1 1
// 5 3

var n = readline().split(" ");
var arr = readline()
	.split(" ")
	.map(function (item) {
		return +item;
	})
	.sort(function (a, b) {
		return a - b;
	})
	.reverse()
	.reduce(
		function (curent, value) {
			curent.push(curent[curent.length - 1] + value);
			return curent;
		},
		[0]
	);
var t = parseInt(n[1]);
while (t--) {
	var q = readline().split(" ");
	var x = parseInt(q[0]);
	var y = parseInt(q[1]);
	write(arr[x] - arr[x - y]);
	print();
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
function readLine() {
    return inputString[currentLine++];
};
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    main();
    // cmd(not powershell): node cp.js < input.txt
});

function main() {
    // let t = parseInt(readLine());
    // while (t-- > 0) {
    solve();
    // }
}
function solve() {
    let [n, q] = readLine().split(" ").map(i => parseInt(i));
    let arr = readLine().split(" ").map(i => parseInt(i)).sort((a, b) => a - b);
    while (q-- > 0) {
        const [x, y] = readLine().split(" ").map(i => parseInt(i));
        let res = 0;
        for (let i = arr.length - x; i <= arr.length - y; i++) {
            res += arr[i];
        }
        console.log(res)
    }

}

// 5 3
// 5 3 1 5 2
// 3 2
// 1 1
// 5 3

var n = readline().split(" ");
var arr = readline()
	.split(" ")
	.map(function (item) {
		return +item;
	})
	.sort(function (a, b) {
		return a - b;
	})
	.reverse()
	.reduce(
		function (curent, value) {
			curent.push(curent[curent.length - 1] + value);
			return curent;
		},
		[0]
	);
var t = parseInt(n[1]);
while (t--) {
	var q = readline().split(" ");
	var x = parseInt(q[0]);
	var y = parseInt(q[1]);
	write(arr[x] - arr[y - 1]);
	print();
}

// 5 3
// 5 3 1 5 2
// 3 2
// 1 1
// 5 3

var n = readline().split(" ");
var arr = readline()
	.split(" ")
	.map(function (item) {
		return +item;
	})
	.sort(function (a, b) {
		return a - b;
	})
	.reverse()
	.reduce(
		function (curent, value) {
			curent.push(curent[curent.length - 1] + value);
			return curent;
		},
		[0]
	);
var t = parseInt(n[1]);
print("arr: ", arr);
while (t--) {
	var q = readline().split(" ");
	var x = parseInt(q[0]);
	var y = parseInt(q[1]);
	write(arr[x] - arr[y - 1]);
	print();
}