You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same. More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that .

The first line contains integer n (1 ≤ n ≤ 5·105), showing how many numbers are in the array. The second line contains n integers a[1], a[2], ..., a[n] (|a[i]| ≤  109) — the elements of array a.

Print a single integer — the number of ways to split the array into three parts with the same sum.

function rda(){ return readline().split(" ").map(Number); };
function rdn(){ return +readline(); };
var n = +readline(), a = rda();
var sum = a.reduce(function(s, cur){ return s + cur; }, 0);

var ans = 0;
if(sum % 3 == 0 && n > 2){
    var part = sum/3;

    var ies = [];
    for(var i = 0, s = 0; i < n-2; i++){
        s += a[i];
        if(s == part){
            ies.push(i);
        }
    }

    var cnt = [];
    for(var i = 0; i < n; i++) cnt[i] = 0;
    for(var i = n-1, s = 0; i >= 2; i--){
        s += a[i];
        if(s == part) cnt[i] = 1;
    }

    var sums = [];
    for(var i = 0; i < n; i++) sums[i] = 0;
    for(var i = n-1, s = 0; i >= 2; i--){
        s += cnt[i];
        sums[i] = s;
    }

    for(var i = 0; i < ies.length; i++){
        ans += sums[ies[i]+2];
    }
}

write(ans);

const N = 1<<19;

var n, arr;
var totalSum, currSum, goalSum, cnt, ans;
var token = [];

function initializeData() {
  arr = new Array(N);
}

initializeData();

n = parseInt(readline());

totalSum=0;

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

if(totalSum%3!=0) {
  print(0);
}
else {
  goalSum=totalSum;
  ans=0;

  if(totalSum<0) {
    goalSum=-totalSum;
    goalSum=Math.floor(goalSum/3);//(goalSum/3>>0);
    goalSum=-goalSum;
  }
  else {
    goalSum=Math.floor(goalSum/3);//(totalSum/3>>0);
  }

  currSum=0;
  cnt=0;

  for(i=1;i<n;i++) {
    currSum+=arr[i];

    if(totalSum-currSum==goalSum) {
      ans+=cnt;
    }

    if(currSum==goalSum) {
      ++cnt;
    }
  }

  print(ans);
}

function ProblemSolver() {
    this.solveCase = function() {
        var res , i , j , a , b , d , e;
        res = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
        }
        if( d % 3 != 0 ) {
            print( res );
            return;
        }
        if( d == 0 ) {
            a = 0;
            for( i = 0 ; i < this.n ; i++ ) {
                a += this.arr[ i ];
                if( a == 0 ) {
                    res++;
                }
            }
            res -= 2;
            res = Math.floor( ( res * ( res + 1 ) ) / 2 );
            print( res );
            return;
        }
        a = d / 3;
        b = a * 2;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == a ) {
                this.brr[ i ] = 1;
            }
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == b ) {
                res += e;
            }
            e += this.brr[ i ];
        }
        print( res );
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

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

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

    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.crr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = 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.crr.push( 0 );
            this.adj_list.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() {
        this.lim1 = 500010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.memsetArray1D = function( arrParam , val ) {
        var i;
        if( arrParam == null ) {
            throw new Error( "No array supplied in the parameter!" );
        }
        if( val == null ) {
            throw new Error( "No value for memset has been supplied in the parameter!" );
        }
        arrParam = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            arrParam.push( val );
        }
        return arrParam;
    };

    this.getStringLength = function( stringData ) {
        var len , lengthType;
        len = stringData.length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = stringData.length();
        }
        else {
            len = stringData.length;
        }
        return len;
    };

    this.init();
}

function InputReader() {
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;

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

    this.readAllLinesFromRhinoStdin = function() {
        importPackage( java.io );
        importPackage( java.lang );
        var singleLine , reader;
        reader = new BufferedReader( new InputStreamReader( System[ "in" ] ) );
        this.allLines = [];
        while( true ) {
            singleLine = reader.readLine();
            if( singleLine != null ) {
                this.allLines.push( singleLine );
            }
            else {
                break;
            }
        }
    };

    this.readAllLinesFromNodeStdin = function() {
        var fsObj , size , rawData;
        process.stdin.setEncoding( 'ascii' );
        fsObj = require( 'fs' );
        size = fsObj.fstatSync( process.stdin.fd ).size;
        rawData = fsObj.readSync( process.stdin.fd , size )[ 0 ];
        this.parseRawData( rawData );
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        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;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx , lengthType;
        len = this.allLines[ this.currrentLineNumber ].length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = this.allLines[ this.currrentLineNumber ].length();
        }
        if( flag == 0 ) {
            res = "";
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( 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;
            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 = -1;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );
            }
            if( endIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            else {
                this.currrentCharacterIndex = endIdx;
            }
            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() {
        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;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

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

    this.runCode = function() {
        var testCases , i , hasMoreTestCases , isLocalMachine , localContext;
        isLocalMachine = false;
        try {
            if( __dirname != null && __dirname.charAt( 1 ) == ':' ) {
                isLocalMachine = true;
            }
        }
        catch( ex ) {
            isLocalMachine = false;
        }
        if( isLocalMachine == true ) {
            //local machine runs on node and relies on file i/o
            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 );
        }
        else {
            //server machine
            try {
                var rlObj = readline;
                //server runs on javasctipt v8 distribution and has readline method on global context
                this.irObj.readAllLines();
            }
            catch( ex ) {
                try {
                    var pObj = process;
                    //server runs on node
                    print = console.log;
                    this.irObj.readAllLinesFromNodeStdin();
                }
                catch( ex ) {
                    try {
                        var ipObj = importPackage;
                        //server runs on rhino
                        this.irObj.readAllLinesFromRhinoStdin();
                    }
                    catch( ex ) {
                        throw new Error( "Unknown javasctipt distribution!" );
                    }
                }
            }
        }
        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.runCode();
}

new CodeExecutioner();

function ProblemSolver() {
    this.solveCase = function() {
        var res , i , j , a , b , c , d , e;
        res = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
        }
        if( d % 3 != 0 ) {
            print( res );
            return;
        }
        if( d == 0 ) {
            a = 0;
            for( i = 0 ; i < this.n ; i++ ) {
                a += this.arr[ i ];
                if( a == 0 ) {
                    res++;
                }
            }
            res -= 2;
            res = Math.floor( ( res * ( res + 1 ) ) / 2 );
            print( res );
            return;
        }
        a = d / 3;
        b = a * 2;
        c = a * 3;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == a ) {
                this.brr[ i ] = 1;
            }
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == b ) {
                res += e;
            }
            e += this.brr[ i ];
        }
        /*
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == c ) {
                res += e;
            }
            e += this.crr[ i ];
        }
        */
        print( res );
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

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

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

    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.crr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = 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.crr.push( 0 );
            this.adj_list.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() {
        this.lim1 = 500010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.memsetArray1D = function( arrParam , val ) {
        var i;
        if( arrParam == null ) {
            throw new Error( "No array supplied in the parameter!" );
        }
        if( val == null ) {
            throw new Error( "No value for memset has been supplied in the parameter!" );
        }
        arrParam = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            arrParam.push( val );
        }
        return arrParam;
    };

    this.getStringLength = function( stringData ) {
        var len , lengthType;
        len = stringData.length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = stringData.length();
        }
        else {
            len = stringData.length;
        }
        return len;
    };

    this.init();
}

function InputReader() {
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;

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

    this.readAllLinesFromRhinoStdin = function() {
        importPackage( java.io );
        importPackage( java.lang );
        var singleLine , reader;
        reader = new BufferedReader( new InputStreamReader( System[ "in" ] ) );
        this.allLines = [];
        while( true ) {
            singleLine = reader.readLine();
            if( singleLine != null ) {
                this.allLines.push( singleLine );
            }
            else {
                break;
            }
        }
    };

    this.readAllLinesFromNodeStdin = function() {
        var fsObj , size , rawData;
        process.stdin.setEncoding( 'ascii' );
        fsObj = require( 'fs' );
        size = fsObj.fstatSync( process.stdin.fd ).size;
        rawData = fsObj.readSync( process.stdin.fd , size )[ 0 ];
        this.parseRawData( rawData );
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        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;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx , lengthType;
        len = this.allLines[ this.currrentLineNumber ].length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = this.allLines[ this.currrentLineNumber ].length();
        }
        if( flag == 0 ) {
            res = "";
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( 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;
            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 = -1;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );
            }
            if( endIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            else {
                this.currrentCharacterIndex = endIdx;
            }
            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() {
        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;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

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

    this.runCode = function() {
        var testCases , i , hasMoreTestCases , isLocalMachine , localContext;
        isLocalMachine = false;
        try {
            if( __dirname != null && __dirname.charAt( 1 ) == ':' ) {
                isLocalMachine = true;
            }
        }
        catch( ex ) {
            isLocalMachine = false;
        }
        if( isLocalMachine == true ) {
            //local machine runs on node and relies on file i/o
            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 );
        }
        else {
            //server machine
            try {
                var rlObj = readline;
                //server runs on javasctipt v8 distribution and has readline method on global context
                this.irObj.readAllLines();
            }
            catch( ex ) {
                try {
                    var pObj = process;
                    //server runs on node
                    print = console.log;
                    this.irObj.readAllLinesFromNodeStdin();
                }
                catch( ex ) {
                    try {
                        var ipObj = importPackage;
                        //server runs on rhino
                        this.irObj.readAllLinesFromRhinoStdin();
                    }
                    catch( ex ) {
                        throw new Error( "Unknown javasctipt distribution!" );
                    }
                }
            }
        }
        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.runCode();
}

new CodeExecutioner();

var elements = readline();
var arr = readline().split(" ").map(Number);

var sum = 0, answer = 0, count = 0, temp_sum = 0;
for(var i = 0; i < elements; ++i) sum = sum + arr[i];

if(sum % 3 == 0) {
  sum = sum / 3;
  for(var i = 0; i < elements - 1; ++i) {
    temp_sum = temp_sum + arr[i];
    if(temp_sum == 2 * sum) answer = answer + count;
    if(temp_sum == sum) count = count + 1;
  }
}

print(answer);

function main() {
    var n = Number(readline());
    var data = readline().split(' ').map(Number);
    var total = data.reduce((prev, val) => prev+val);
    if(total%3!=0){
        return print(0);
    }

    var sums = [];
    for(var i=0;i<n;i++){
        sums[i] = 0;
    }
    var sum =0;
    for(var i=n-1;i>=0;i--){
        sum += data[i];
        if(sum == total/3){
            sums[i] = 1;
        }
    }
    for(var i=n-2;i>=0;i--){
        sums[i] = sums[i] + sums[i+1];
    }
    sum = 0;
    var res= 0;
    for(var i=0;i<n-2;i++){
        sum+= data[i];
        if(sum == total/3){
            res += sums[i+2];
        }
    }
    print(res)
}

main()

var writeResult = function (result) {
    write(result);
    quit();
};

var n = +readline();

if (n < 3) {
    writeResult(0);
}

var a = readline().split(' ').map(value => +value);
a.unshift(0);

for (var i = 1; i <= n; ++i) {
    a[i] += a[i - 1];
}

var s = a[n];

if (s === 0) {
    var zeroCount = 0;

    for (i = 1; i <= n; ++i) {
        if (a[i] === 0)
            ++zeroCount;
    }

    writeResult(zeroCount < 3 ? 0 : (zeroCount - 1) * (zeroCount - 2) / 2);
}

if (s % 3) {
    writeResult(0);
}

var third = s / 3;
var twothirds = s - third;

var b = new Array(n + 1).fill(0);
for (i = n - 1; i >= 1; --i) {
    b[i] = b[i + 1] + (a[i] === twothirds ? 1 : 0);
}

var result = 0;
for (i = 1; i <= n; ++i) {
    if (a[i] === third) {
        result += b[i];
    }
}

write(result);

var writeResult = function(result) {
  write(result)
  quit();
}

var n = +readline();

if (n < 3) {
  writeResult(0);
}

var a = readline().split(' ').map(value => +value);

a.unshift(0);

for (var i = 2; i <= n; ++i) {
  a[i] += a[i-1];
}

var S = a[n];

if (S === 0) {
  var cnt = 0;
  for (var i = 1; i <= n; ++i) {
    if (a[i] === 0)
      ++cnt;
  }

  if (cnt < 3) {
     writeResult(0);
  } else {
     writeResult((cnt-1)*(cnt-2)/2);
  }
}

if (S%3) {
  writeResult(0);
}

var x = S/3;
var y = 2*x;

var cx = [];
cx[1] = 0;
for (var i = 2; i <= n; ++i) {
  cx[i] = cx[i-1] + (a[i] === x ? 1 : 0);
}

var cy = [];
cy[n] = 0;
for (var i = n-1; i >= 1; --i) {
  cy[i] = cy[i+1] + (a[i] === y ? 1 : 0);
}

var result = 0;
for (var i = 1; i <= n; ++i) {
  if (a[i] === x) {
     result += cy[i];
  }
}

write(result);

n = Number(readline());
a = readline().split(' ').map(Number);
var sum = [];
var cnt = [];
sum = 0;
count = 0;

for (var i = 0; i < n; i++) sum += a[i];
part = sum / 3;
if (sum % 3 !== 0) write(0);
else {
    sum = a[n-1]
    cnt[n-1] = Number(sum === part);
    for (var i = n - 2; i >= 0; i--) {
        sum += a[i];
        cnt[i] = cnt[i+1] + (sum === part);
    }
    cnt[n] = 0;
    // print(cnt);
    sum = 0
    for (var i = 0; i < n-2; i++) {
        sum += a[i];
        if (sum === part) count+= cnt[i+2];
    }
    write(count);
}

const N = 1<<19;

var n, arr;
var totalSum, currSum, goalSum, cnt, ans;
var token = [];

function initializeData() {
  arr = new Array(N);
}

initializeData();

n = parseInt(readline());

totalSum=0;

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

if(totalSum%3!=0) {
  print(0);
}
else {
  goalSum=totalSum;
  ans=0;

  if(totalSum<0) {
    goalSum=-totalSum;
    goalSum=(goalSum/3>>0);
    goalSum=-goalSum;
  }
  else {
    goalSum=(totalSum/3>>0);
  }

  currSum=0;
  cnt=0;

  for(i=1;i<n;i++) {
    currSum+=arr[i];

    if(totalSum-currSum==goalSum) {
      ans+=cnt;
    }

    if(currSum==goalSum) {
      ++cnt;
    }
  }

  print(ans);
}

function ProblemSolver() {
    this.solveCase = function() {
        var res , i , j , a , b , c , d , e;
        res = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
        }
        if( d % 3 != 0 ) {
            print( res );
            return;
        }
        if( d == 0 ) {
            a = 0;
            for( i = 0 ; i < this.n ; i++ ) {
                a += this.arr[ i ];
                if( a == 0 ) {
                    res++;
                }
            }
            res -= 2;
            print( res );
            return;
        }
        a = d / 3;
        b = a * 2;
        c = a * 3;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d % a == 0 ) {
                this.brr[ i ] = 1;
            }
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d % b == 0 ) {
                this.crr[ i ] = e;
                e = 0;
            }
            e += this.brr[ i ];
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d % c == 0 ) {
                res += e;
            }
            e += this.crr[ i ];
        }
        print( res );
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

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

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        //this.clearArraysPerCase() ;
    };

    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.crr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = 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.crr.push( 0 );
            this.adj_list.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() {
        this.lim1 = 500010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.memsetArray1D = function( arrParam , val ) {
        var i;
        if( arrParam == null ) {
            throw new Error( "No array supplied in the parameter!" );
        }
        if( val == null ) {
            throw new Error( "No value for memset has been supplied in the parameter!" );
        }
        arrParam = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            arrParam.push( val );
        }
        return arrParam;
    };

    this.getStringLength = function( stringData ) {
        var len , lengthType;
        len = stringData.length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = stringData.length();
        }
        else {
            len = stringData.length;
        }
        return len;
    };

    this.init();
}

function InputReader() {
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;

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

    this.readAllLinesFromRhinoStdin = function() {
        importPackage( java.io );
        importPackage( java.lang );
        var singleLine , reader;
        reader = new BufferedReader( new InputStreamReader( System[ "in" ] ) );
        this.allLines = [];
        while( true ) {
            singleLine = reader.readLine();
            if( singleLine != null ) {
                this.allLines.push( singleLine );
            }
            else {
                break;
            }
        }
    };

    this.readAllLinesFromNodeStdin = function() {
        var fsObj , size , rawData;
        process.stdin.setEncoding( 'ascii' );
        fsObj = require( 'fs' );
        size = fsObj.fstatSync( process.stdin.fd ).size;
        rawData = fsObj.readSync( process.stdin.fd , size )[ 0 ];
        this.parseRawData( rawData );
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        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;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx , lengthType;
        len = this.allLines[ this.currrentLineNumber ].length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = this.allLines[ this.currrentLineNumber ].length();
        }
        if( flag == 0 ) {
            res = "";
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( 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;
            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 = -1;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );
            }
            if( endIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            else {
                this.currrentCharacterIndex = endIdx;
            }
            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() {
        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;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

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

    this.runCode = function() {
        var testCases , i , hasMoreTestCases , isLocalMachine , localContext;
        isLocalMachine = false;
        try {
            if( __dirname != null && __dirname.charAt( 1 ) == ':' ) {
                isLocalMachine = true;
            }
        }
        catch( ex ) {
            isLocalMachine = false;
        }
        if( isLocalMachine == true ) {
            //local machine runs on node and relies on file i/o
            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 );
        }
        else {
            //server machine
            try {
                var rlObj = readline;
                //server runs on javasctipt v8 distribution and has readline method on global context
                this.irObj.readAllLines();
            }
            catch( ex ) {
                try {
                    var pObj = process;
                    //server runs on node
                    print = console.log;
                    this.irObj.readAllLinesFromNodeStdin();
                }
                catch( ex ) {
                    try {
                        var ipObj = importPackage;
                        //server runs on rhino
                        this.irObj.readAllLinesFromRhinoStdin();
                    }
                    catch( ex ) {
                        throw new Error( "Unknown javasctipt distribution!" );
                    }
                }
            }
        }
        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.runCode();
}

new CodeExecutioner();

function ProblemSolver() {
    this.solveCase = function() {
        var res , i , j , a , b , c , d , e;
        res = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
        }
        if( d % 3 != 0 ) {
            print( res );
            return;
        }
        if( d == 0 ) {
            a = 0;
            for( i = 0 ; i < this.n ; i++ ) {
                a += this.arr[ i ];
                if( a == 0 ) {
                    res++;
                }
            }
            res -= 2;
            res = Math.floor( ( res * ( res + 1 ) ) / 2 );
            print( res );
            return;
        }
        a = d / 3;
        b = a * 2;
        c = a * 3;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d % a == 0 ) {
                this.brr[ i ] = 1;
            }
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d % b == 0 ) {
                this.crr[ i ] = e;
                e = 0;
            }
            e += this.brr[ i ];
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d % c == 0 ) {
                res += e;
            }
            e += this.crr[ i ];
        }
        print( res );
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

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

    this.clearPerCase = function() {
        this.cn = 0;
        this.cc++;
        //this.clearArraysPerCase() ;
    };

    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.crr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = 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.crr.push( 0 );
            this.adj_list.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() {
        this.lim1 = 500010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.memsetArray1D = function( arrParam , val ) {
        var i;
        if( arrParam == null ) {
            throw new Error( "No array supplied in the parameter!" );
        }
        if( val == null ) {
            throw new Error( "No value for memset has been supplied in the parameter!" );
        }
        arrParam = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            arrParam.push( val );
        }
        return arrParam;
    };

    this.getStringLength = function( stringData ) {
        var len , lengthType;
        len = stringData.length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = stringData.length();
        }
        else {
            len = stringData.length;
        }
        return len;
    };

    this.init();
}

function InputReader() {
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;

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

    this.readAllLinesFromRhinoStdin = function() {
        importPackage( java.io );
        importPackage( java.lang );
        var singleLine , reader;
        reader = new BufferedReader( new InputStreamReader( System[ "in" ] ) );
        this.allLines = [];
        while( true ) {
            singleLine = reader.readLine();
            if( singleLine != null ) {
                this.allLines.push( singleLine );
            }
            else {
                break;
            }
        }
    };

    this.readAllLinesFromNodeStdin = function() {
        var fsObj , size , rawData;
        process.stdin.setEncoding( 'ascii' );
        fsObj = require( 'fs' );
        size = fsObj.fstatSync( process.stdin.fd ).size;
        rawData = fsObj.readSync( process.stdin.fd , size )[ 0 ];
        this.parseRawData( rawData );
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        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;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx , lengthType;
        len = this.allLines[ this.currrentLineNumber ].length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = this.allLines[ this.currrentLineNumber ].length();
        }
        if( flag == 0 ) {
            res = "";
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( 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;
            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 = -1;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );
            }
            if( endIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            else {
                this.currrentCharacterIndex = endIdx;
            }
            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() {
        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;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

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

    this.runCode = function() {
        var testCases , i , hasMoreTestCases , isLocalMachine , localContext;
        isLocalMachine = false;
        try {
            if( __dirname != null && __dirname.charAt( 1 ) == ':' ) {
                isLocalMachine = true;
            }
        }
        catch( ex ) {
            isLocalMachine = false;
        }
        if( isLocalMachine == true ) {
            //local machine runs on node and relies on file i/o
            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 );
        }
        else {
            //server machine
            try {
                var rlObj = readline;
                //server runs on javasctipt v8 distribution and has readline method on global context
                this.irObj.readAllLines();
            }
            catch( ex ) {
                try {
                    var pObj = process;
                    //server runs on node
                    print = console.log;
                    this.irObj.readAllLinesFromNodeStdin();
                }
                catch( ex ) {
                    try {
                        var ipObj = importPackage;
                        //server runs on rhino
                        this.irObj.readAllLinesFromRhinoStdin();
                    }
                    catch( ex ) {
                        throw new Error( "Unknown javasctipt distribution!" );
                    }
                }
            }
        }
        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.runCode();
}

new CodeExecutioner();

function ProblemSolver() {
    this.solveCase = function() {
        var res , i , j , a , b , c , d , e;
        res = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
        }
        if( d % 3 != 0 ) {
            print( res );
            return;
        }
        if( d == 0 ) {
            a = 0;
            for( i = 0 ; i < this.n ; i++ ) {
                a += this.arr[ i ];
                if( a == 0 ) {
                    res++;
                }
            }
            res -= 2;
            res = Math.floor( ( res * ( res + 1 ) ) / 2 );
            print( res );
            return;
        }
        a = d / 3;
        b = a * 2;
        c = a * 3;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == a ) {
                this.brr[ i ] = 1;
            }
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == b ) {
                this.crr[ i ] = e;
            }
            e += this.brr[ i ];
        }
        e = 0;
        d = 0;
        for( i = 0 ; i < this.n ; i++ ) {
            d += this.arr[ i ];
            if( d == c ) {
                res += e;
            }
            e += this.crr[ i ];
        }
        print( res );
    };

    this.getInput = function( irObj ) {
        var hasMoreInput , i;
        hasMoreInput = true;
        try {
            this.n = irObj.nextInt();
            for( i = 0 ; i < this.n ; i++ ) {
                this.arr[ i ] = irObj.nextInt();
            }
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

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

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

    this.HAS_TEST_CASES = false;
    this.INPUT_FILE_NAME = "test.in";
    this.OUTPUT_FILE_NAME = "out.txt";
    this.DO_OUTPUT_TO_FILE = false;

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.crr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.adj_list = 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.crr.push( 0 );
            this.adj_list.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() {
        this.lim1 = 500010;
        this.lim2 = 110;
        this.cc = 1;
        this.ind = 1;
        this.n = 0;
        this.cn = 0;
        this.declareAndFillArrays();
    };

    this.memsetArray1D = function( arrParam , val ) {
        var i;
        if( arrParam == null ) {
            throw new Error( "No array supplied in the parameter!" );
        }
        if( val == null ) {
            throw new Error( "No value for memset has been supplied in the parameter!" );
        }
        arrParam = new Array();
        for( i = 0 ; i < this.lim1 ; i++ ) {
            arrParam.push( val );
        }
        return arrParam;
    };

    this.getStringLength = function( stringData ) {
        var len , lengthType;
        len = stringData.length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = stringData.length();
        }
        else {
            len = stringData.length;
        }
        return len;
    };

    this.init();
}

function InputReader() {
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;

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

    this.readAllLinesFromRhinoStdin = function() {
        importPackage( java.io );
        importPackage( java.lang );
        var singleLine , reader;
        reader = new BufferedReader( new InputStreamReader( System[ "in" ] ) );
        this.allLines = [];
        while( true ) {
            singleLine = reader.readLine();
            if( singleLine != null ) {
                this.allLines.push( singleLine );
            }
            else {
                break;
            }
        }
    };

    this.readAllLinesFromNodeStdin = function() {
        var fsObj , size , rawData;
        process.stdin.setEncoding( 'ascii' );
        fsObj = require( 'fs' );
        size = fsObj.fstatSync( process.stdin.fd ).size;
        rawData = fsObj.readSync( process.stdin.fd , size )[ 0 ];
        this.parseRawData( rawData );
    };

    this.parseRawData = function( data ) {
        var len , i , currentString;
        len = data.length;
        currentString = "";
        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;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

    this.next = function( flag ) {
        var len , i , startIdx , res , endIdx , lengthType;
        len = this.allLines[ this.currrentLineNumber ].length;
        lengthType = typeof len;
        if( lengthType == "function" ) {
            len = this.allLines[ this.currrentLineNumber ].length();
        }
        if( flag == 0 ) {
            res = "";
            for( i = this.currrentCharacterIndex ; i < len ; i++ ) {
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( 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;
            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 = -1;
            for( i = startIdx ; i < len ; i++ ) {
                if( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) == ' '.charCodeAt( 0 ) ) {
                    endIdx = i;
                    break;
                }
                res += String.fromCharCode( this.allLines[ this.currrentLineNumber ].charCodeAt( i ) );
            }
            if( endIdx == -1 ) {
                this.currrentLineNumber++;
                this.currrentCharacterIndex = 0;
            }
            else {
                this.currrentCharacterIndex = endIdx;
            }
            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() {
        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;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

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

    this.runCode = function() {
        var testCases , i , hasMoreTestCases , isLocalMachine , localContext;
        isLocalMachine = false;
        try {
            if( __dirname != null && __dirname.charAt( 1 ) == ':' ) {
                isLocalMachine = true;
            }
        }
        catch( ex ) {
            isLocalMachine = false;
        }
        if( isLocalMachine == true ) {
            //local machine runs on node and relies on file i/o
            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 );
        }
        else {
            //server machine
            try {
                var rlObj = readline;
                //server runs on javasctipt v8 distribution and has readline method on global context
                this.irObj.readAllLines();
            }
            catch( ex ) {
                try {
                    var pObj = process;
                    //server runs on node
                    print = console.log;
                    this.irObj.readAllLinesFromNodeStdin();
                }
                catch( ex ) {
                    try {
                        var ipObj = importPackage;
                        //server runs on rhino
                        this.irObj.readAllLinesFromRhinoStdin();
                    }
                    catch( ex ) {
                        throw new Error( "Unknown javasctipt distribution!" );
                    }
                }
            }
        }
        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.runCode();
}

new CodeExecutioner();

function main() {
    var a = readline();
    var data = readline().split(' ').map(Number);
    var n  =data.length;
    var start = [data[0]];
    var finish = [data[n-1]];
    var total = start[0];
    for(var i=1;i<n;i++){
        start[i] = start[i-1] + data[i];
        total += data[i];
    }
    for(var i = n-2;i>=0;i--){
        finish[i] = finish[i+1] + data[i];
    }
    if(n<3){
        return print(0);
    }
    var i = 0;
    var sum1 = data[0];
    var j = n-1;
    var sum2 = data[n-1];
    var sum3 = total;
    var res = 0;
    while(i<j){
        sum3 = total - sum1 - sum2;
        if(sum1 == sum2  && sum2 == sum3){
            res+=1;
            if(data[j-1] == 0){
                j--;
                sum2 += data[j]
            } else if(data[i+1]==0){
                i++;
                sum1 += data[i]
            } else {
              i++;
              sum1 += data[i]
              j--;
              sum2 += data[j]
            }
            continue;
        }
        if(sum1 < sum2){
            i++
            sum1 += data[i]
        } else {
            j--;
            sum2 += data[j]
        }
    }
    print(res);
}

main()

var writeResult = function(result) {
  write(result)
  quit();
}

var n = +readline();

if (n < 3) {
  writeResult(0);
}

var a = readline().split(' ').map(value => +value);

a.unshift(0);

for (var i = 2; i <= n; ++i) {
  a[i] += a[i-1];
}

var S = a[n];

if (S === 0) {
  var cnt = 0;
  for (var i = 1; i <= n; ++i) {
    if (a[i] === 0)
      ++cnt;
  }

  if (cnt < 3) {
     writeResult(0);
  } else {
     writeResult(cnt*(cnt-1)/2);
  }
}

if (S%3) {
  writeResult(0);
}

var x = S/3;
var y = 2*x;

var cx = [];
cx[1] = 0;
for (var i = 2; i <= n; ++i) {
  cx[i] = cx[i-1] + (a[i] === x ? 1 : 0);
}

var cy = [];
cy[n] = 0;
for (var i = n-1; i >= 1; --i) {
  cy[i] = cy[i+1] + (a[i] === y ? 1 : 0);
}

var result = 0;
for (var i = 1; i <= n; ++i) {
  if (a[i] === x) {
     result += cy[i];
  }
}

write(result);

function checkNeib(res, value) {
	var count = 0;
	tmp = res;
	while (tmp < sum.length) {
		if (sum[sum.length-1] - sum[tmp] == sum[value]) count++;
		else break;
		tmp++;
	}
	tmp = res - 1;
	while (tmp > 0) {
		if (sum[sum.length-1] - sum[tmp] == sum[value]) count++;
		else break;
		tmp--;
	}
	return count;
}

function binarySearch(left, right, value) {
    var middle = (left + right) >> 1;
    if (sum[value] == sum[middle] - sum[value]) {
		return checkNeib(middle, value);
	}
    if (left >= right) return 0;
    if (sum[middle] - sum[value] > sum[value]) return binarySearch(left, middle, value);
    else if (sum[middle] - sum[value] < sum[value]) return binarySearch(middle+1, right, value);
}

n = Number(readline());
a = readline().split(' ').map(Number);
var sum = [];
sum[0] = a[0];
for (var i = 1; i < n; i++) {
    sum[i] = sum[i-1] + a[i];
}

var sum1 = 0;
var count = 0;
for (var i = 0; i < n; i++) {
    sum1 = sum[i];
    count += binarySearch(i+1, n, i);
    // print(i, count);
}
write(count);


You are given an array consisting of all integers from $$$[l, r]$$$ inclusive. For example, if $$$l = 2$$$ and $$$r = 5$$$, the array would be $$$[2, 3, 4, 5]$$$. What's the minimum number of elements you can delete to make the bitwise AND of the array non-zero?A bitwise AND is a binary operation that takes two equal-length binary representations and performs the AND operation on each pair of the corresponding bits.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq 2 \cdot 10^5$$$) — the description of the array.

For each test case, output a single integer — the answer to the problem.

NoteIn the first test case, the array is $$$[1, 2]$$$. Currently, the bitwise AND is $$$0$$$, as $$$1\ \& \ 2 = 0$$$. However, after deleting $$$1$$$ (or $$$2$$$), the array becomes $$$[2]$$$ (or $$$[1]$$$), and the bitwise AND becomes $$$2$$$ (or $$$1$$$). This can be proven to be the optimal, so the answer is $$$1$$$.In the second test case, the array is $$$[2, 3, 4, 5, 6, 7, 8]$$$. Currently, the bitwise AND is $$$0$$$. However, after deleting $$$4$$$, $$$5$$$, and $$$8$$$, the array becomes $$$[2, 3, 6, 7]$$$, and the bitwise AND becomes $$$2$$$. This can be proven to be the optimal, so the answer is $$$3$$$. Note that there may be other ways to delete $$$3$$$ elements.

"use strict";
const fs = require("fs");
//let filename = "0.txt";
let filename = 0;
const input = fs.readFileSync(filename, "utf8").trim().split("\n");
let line = 0;
function readline() {
  return input[line++];
}
function iInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => parseInt(cur));
}
function BInpArr() {
  return readline()
    .trim()
    .split(" ")
    .map((cur) => BigInt(cur));
}
function string() {
  return readline().trim();
}
function stringArr() {
  return readline().trim().split("");
}

function stringArr1() {
  return readline().trim().split(" ");
}
function getValue() {
  return parseInt(readline());
}
function iInpArr1() {
  return readline()
    .trim()
    .split("")
    .map((cur) => parseInt(cur));
}
let mod = 1e9 + 7;
mod = BigInt(mod);
const pow = (num, exp, mod) => {
  if (exp === BigInt(0)) return BigInt(1);
  let x = pow(num, exp / BigInt(2), mod);
  if (exp % BigInt(2)) return (((x * x) % mod) * num) % mod;
  else return (x * x) % mod;
};
const inverse = (num, exp) => {
  return pow(BigInt(num), BigInt(exp), BigInt(mod));
};
const sqrt = (n) => {
  let low = 1n,
    high = n,
    ans;
  while (low <= high) {
    let mid = (low + high) / 2n;
    if (mid * mid <= n) {
      ans = mid;
      low = mid + 1n;
    } else high = mid - 1n;
  }
  return ans;
};
let maxv = 2e5;
let bit = new Array(maxv + 1);
bit[0] = new Array(20).fill(0);
const blackbox = () => {
  for (let i = 1; i <= maxv; i++) {
    let val = i,
      k = new Array(20).fill(0),
      j = 0;
    while (val > 0) {
      if (val & 1) k[j] += bit[i - 1][j] + 1;
      else k[j] += bit[i - 1][j];
      j++;
      val = val >> 1;
    }
    bit[i] = k;
  }
};
const solve = () => {
  blackbox();
  let t = getValue();
  while (t--) {
    let [l, r] = iInpArr();
    let res = [],
      max = Infinity,
      to = r - l + 1;
    for (let i = 0; i < 20; i++) {
      res[i] = bit[r][i] - bit[l - 1][i];
      max = Math.min(max, to - res[i]);
    }
    console.log(max);
  }
};
solve();

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

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

function main() {
  const xx = readline();
  var array = []
  array[0] = new Array(20).fill(0)

// for (let i = 1; i < 2*Math.pow(10, 5); i++) {
  for (let i = 1; i < 200000 + 1; i++) {
    array[i] = array[i - 1].slice()
    var value = dec2bin(i)

    for (let j = 0; j < 20 && j < value.length; j++) {
      array[i][j] += value[j] === '0' ? 1 : 0
    }
  }
  // console.log(array)

  Array(Number(xx)).fill(1).map((t, i) => {
    // const n = Number(readline());

    var [l, r] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })
    if (l === r) return console.log(0)
    // console.log(array[l], array[r])
    l = l - 1
    var min = Number.MAX_SAFE_INTEGER
    var show = new Array(20).fill(0)
    for (let j = 0; j < Math.ceil(Math.log2(r)) + 1; j++) {
      show[j] = array[r][j] - array[l][j]
      if (array[l][j] !== 0 || array[r][j] !== 0)
        min = Math.min(min, Math.abs(array[r][j] - array[l][j]))
    }
    console.log(min)
    // console.log(show.toString())
    // console.log(array[l].toString())
    // console.log(array[r].toString())
    // var a = readline().split(' ').map((x, iii) => {
    //   sum+=Number(x)
    //   return Number(x)
    // })
    // console.log(sum)

// console.log(a)
// console.log(n)
    // if(i===(string.length-2)) return console.log(string)
  })
}

function dec2bin(dec) {
  var string = (dec >>> 0).toString(2);
  var front = ''
  for (let i = 0; i < 20 - string.length; i++) {
    front += '0'
  }
  return (front + string).split("").reverse().join("")
}

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

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

function main () {
	let T = rn();
	while (T--) {
		let [l, r] = rna();
		l++, r++;

		function countOnes (x, pos) {
			const k = 2**pos;
			return Math.floor(x/k)*k/2 + Math.max(0, x%k - k/2);
		}

		let ans = 0;
		for (let pos = 1; pos <= 20; pos++) {
			ans = Math.max(ans, countOnes(r, pos) - countOnes(l-1, pos));
		}

		console.log(r-l+1-ans);
	}
}

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

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

function main() {
  const xx = readline();
  var array = []
  array[0] = new Array(20).fill(0)

// for (let i = 1; i < 2*Math.pow(10, 5); i++) {
  for (let i = 1; i < 200000 + 1; i++) {
    array[i] = array[i - 1].slice()
    var value = dec2bin(i)

    for (let j = 0; j < 20 && j < value.length; j++) {
      array[i][j] += value[j] === '0' ? 1 : 0
    }
  }
  // console.log(array)

  Array(Number(xx)).fill(1).map((t, i) => {
    // const n = Number(readline());

    var [l, r] = readline().split(' ').map((x, iii) => {
      return parseInt(x)
    })

    // console.log(array[l], array[r])
    l = l - 1
    var min = Number.MAX_SAFE_INTEGER
    var show = new Array(20).fill(0)
    for (let j = 0; j < Math.ceil(Math.log2(r)) + 1; j++) {
      show[j] = array[r][j] - array[l][j]
      if (array[l][j] !== 0 || array[r][j] !== 0)
        min = Math.min(min, Math.abs(array[r][j] - array[l][j]))
    }
    console.log(min)
    // console.log(show.toString())
    // console.log(array[l].toString())
    // console.log(array[r].toString())
    // var a = readline().split(' ').map((x, iii) => {
    //   sum+=Number(x)
    //   return Number(x)
    // })
    // console.log(sum)

// console.log(a)
// console.log(n)
    // if(i===(string.length-2)) return console.log(string)
  })
}

function dec2bin(dec) {
  var string = (dec >>> 0).toString(2);
  var front = ''
  for (let i = 0; i < 20 - string.length; i++) {
    front += '0'
  }
  return (front + string).split("").reverse().join("")
}


After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:  There is at least one digit in the string,  There is at least one lowercase (small) letter of the Latin alphabet in the string,  There is at least one of three listed symbols in the string: '#', '*', '&'.   Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.

The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols.  Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password.

Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.

NoteIn the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.   In the second test one of possible algorithms will be:   to move the pointer of the second symbol once to the right.  to move the pointer of the third symbol twice to the right.

function isNumber(symbol){
    if(!symbol){
        return false
    }
    var code = symbol.charCodeAt()
    return code >= 48 && code <= 57;
}

function isChar(symbol){
    if(!symbol){
        return false
    }
    var code = symbol.charCodeAt();
    return code >= 97 && code<=122
}

function isSpec(symbol){
    if(!symbol){
        return false
    }
    var code = symbol.charCodeAt();
    return code == 35 || code==38 || code==42
}

function main() {
    var n = Number(readline().split(' ')[0]);
    var strings = [];
    for(var i=0;i<n;i++){
        strings.push(readline());
    }
    var data = [];

    for(var i=0;i<n;i++){
        data[i] = {
            number: Number.MAX_VALUE,
            symbol: Number.MAX_VALUE,
            spec: Number.MAX_VALUE,
        };
        for(var j=0;j<strings[0].length;j++){
            var k = strings[0].length-j;
            if(isNumber(strings[i][j]) || isNumber(strings[i][k])){
                data[i].number=j;
                break;
            }
        }
        for(var j=0;j<strings[0].length;j++){
            var k = strings[0].length-j;
            if(isChar(strings[i][j]) || isChar(strings[i][k])){
                data[i].symbol=j;
                break;
            }
        }
        for(var j=0;j<strings[0].length;j++){
            var k = strings[0].length-j;
            if(isSpec(strings[i][j]) || isSpec(strings[i][k])){
                data[i].spec=j;
                break;
            }
        }
    }
    var max = Number.MAX_VALUE
    for(var i=0;i<n;i++){
        for(var j=0;j<n;j++){
            if(j == i){
                continue;
            }
            for(var k=0;k<n;k++){
                if(k == j || k ==i){
                    continue;
                }
                var pos = data[i].number + data[j].symbol + data[k].spec;
                if(pos < max){
                    max = pos
                }
            }
        }
    }
    print(max);
}

main()


Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |x - y| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is .Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to y (1 ≤ x, y ≤ n), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 105). The next line contains m integers separated by spaces: a1, a2, ..., am (1 ≤ ai ≤ n).

Print a single integer — the minimum number of pages Ryouko needs to turn.

NoteIn the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1, 2, 3, 3, 3, 2}, so the number of pages Ryouko needs to turn is |1 - 2| + |2 - 3| + |3 - 3| + |3 - 3| + |3 - 2| = 3.In the second sample, optimal solution is achieved by merging page 9 to 4.

t=readline().split(' ');
n=+t[0]; m=+t[1]; S=0;
a=readline().split(' ');
A=new Array(n+1);
B=new Array(n+1);
for(i=1;i<m;++i)if((x=+a[i-1])!==(y=+a[i])){
  if(B[x])B[x].push(y);
  else B[x]=[y];
  if(B[y])B[y].push(x);
  else B[y]=[x];
  S+=z=Math.abs(x-y);
  if(A[x])A[x]+=z;
  else A[x]=z;
  if(A[y])A[y]+=z;
  else A[y]=z;
}
m=0;
function equ(a,b){return a-b;}
for(i in A){
  t=B[i];
  t.sort(equ);
  z=t[t.length/2|0];
  s=0;
  for(j=t.length;j--;)s+=Math.abs(t[j]-z);
  s=A[i]-s;
  if(s>m)m=s;
}
print(S-m);


Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.

The first line contains integer n (1 ≤ n ≤ 105) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.  The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.

In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.

7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3

NotePlease note that Dima got a good old kick in the pants for the second sample from the statement.

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function solve(words, text) {
	var dfa = { position: 0 };
	dfa.message = '<3' + words.join('<3') + '<3';
	for (var i = 0; i < text.length; ++i) {
		if (text.charAt(i) == dfa.message.charAt(dfa.position)) {
			dfa.position += 1;
			if (dfa.position == dfa.message.length) {
				return true;
			}
		}
	}
	return false;
}

function main() {
	var wordNum = parseInt(readline());
	var words = [];
	for (var i = 0; i < wordNum; ++i) {
		words.push(trim(readline()));
	}
	var text = trim(readline());
	print(solve(words, text) ? 'yes' : 'no');
}

main();

n = Number(readline());
var text = [];
while (n--) {
    str = readline();
    text.push(str);
}
var main = readline();

var original = '<3';
for (var i = 0; i < text.length; i++)
    original += (text[i] + '<3');
var j = 0;

for (var i = 0; i < main.length; i++) {
    if (main[i] == original[j]) j++;
}

write((j == original.length) ? 'yes' : 'no');

//var input = "7\ni\nam\nnot\nmain\nin\nthe\nfamily\n<3i<>3am<3the<3<main<3in<3the<3><3family<3";
//var index = 0;
//
//function readline(){
//    var data = input.split('\n');
//    if(index < data.length)
//        return data[index++];
//}
//
//function print(output){
//    console.log(output);
//}

function main(){
    var n = readline();
    var ans = "";
    for(var i = 0; i < n; i++){
        ans += '<3' + readline();
        if(i == n - 1)
            ans += '<3';
    }
    var text = readline();
    var index = 0;
    for(var i = 0; i < text.length; i++){
        if(text.charAt(i) == ans.charAt(index))
            index++;
        if(index == ans.length){
            print('yes');
            return;
        }

    }
    print('no');
}
main();

n = Number(readline());
var text = [];
while (n--) {
    str = readline();
    text.push(str);
}
var main = readline();
var result = true;

for (var i = 0; i < text.length; i++) {
    var template = '<.*?3.*?';
    for (var j = 0; j < text[i].length; j++)
        template += (text[i][j] + '.*?')
    template += '<.*?3.*?';
    re = new RegExp(template);
    result &= re.test(main);
    if (!result) break;
    main = main.replace(re, '<3');
}
write(result ? 'YES' : 'NO');


Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies.All elements are enumerated with integers. The ChemForces company has discovered $$$n$$$ distinct chemical elements with indices $$$a_1, a_2, \ldots, a_n$$$, and will get an income of $$$x_i$$$ Berland rubles if the $$$i$$$-th element from this list is in the set of this company.The TopChemist company discovered $$$m$$$ distinct chemical elements with indices $$$b_1, b_2, \ldots, b_m$$$, and it will get an income of $$$y_j$$$ Berland rubles for including the $$$j$$$-th element from this list to its set.In other words, the first company can present any subset of elements from $$$\{a_1, a_2, \ldots, a_n\}$$$ (possibly empty subset), the second company can present any subset of elements from $$$\{b_1, b_2, \ldots, b_m\}$$$ (possibly empty subset). There shouldn't be equal elements in the subsets.Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$)  — the number of elements discovered by ChemForces. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$x_i$$$ ($$$1 \leq a_i \leq 10^9$$$, $$$1 \leq x_i \leq 10^9$$$)  — the index of the $$$i$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$a_i$$$ are distinct. The next line contains a single integer $$$m$$$ ($$$1 \leq m \leq 10^5$$$)  — the number of chemicals invented by TopChemist. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$b_j$$$ and $$$y_j$$$, ($$$1 \leq b_j \leq 10^9$$$, $$$1 \leq y_j \leq 10^9$$$)  — the index of the $$$j$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$b_j$$$ are distinct.

Print the maximum total income you can obtain by choosing the sets for both companies in such a way that no element is presented in both sets.

NoteIn the first example ChemForces can choose the set ($$$3, 7$$$), while TopChemist can choose ($$$1, 2, 4$$$). This way the total income is $$$(10 + 2) + (4 + 4 + 4) = 24$$$.In the second example ChemForces can choose the only element $$$10^9$$$, while TopChemist can choose ($$$14, 92, 35$$$). This way the total income is $$$(239) + (15 + 65 + 89) = 408$$$.

  var a = [];
  var x = [];
  var b = [];
  var y = [];
  var na = parseInt(readline());
  for(var i = 0; i < na; i += 1) {
    var tmp = readline().split(' ').map(x => parseInt(x));
    a.push(tmp);
  }
  var nb = parseInt(readline());
  for(var i = 0; i < nb; i += 1) {
    var tmp = readline().split(' ').map(x => parseInt(x));
    b.push(tmp);
  }

  a.sort(function(a, b) {
    return a[0] - b[0];
  })

  b.sort(function(a, b) {
    return a[0] - b[0];
  })

  var res = 0;
  var i = 0;
  var j = 0;
  while(i < na && j < nb) {
    if(a[i][0] < b[j][0]) {
      res += a[i][1];
      i += 1;
    } else if(a[i][0] == b[j][0]) {
      if(a[i][1] < b[j][1]) {
        res += b[j][1];
      } else {
        res += a[i][1];
      }
      i += 1;
      j += 1;
    } else {
      res += b[j][1];
      j += 1;
    }
  }
  while(i < na) {
    res += a[i][1];
    i += 1;
  }
  while(j < nb) {
    res += b[j][1];
    j += 1;
  }

  print(res);