After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.

The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.  The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.

Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.

var n = +readline(), s = readline().split("");
var keys = {}, cnt = 0;

for(i = 0; i < s.length; i += 2){
	if(keys[s[i]] == undefined){
		keys[s[i]] = 1;
	}
	else{
		keys[s[i]]++;
	}

	if(keys[s[i+1].toLowerCase()] != undefined && keys[s[i+1].toLowerCase()] > 0){
		keys[s[i+1].toLowerCase()]--;
	}
	else{
		cnt++;
	}
}

write(cnt);

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

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , len ;
        res = 0 ;
        len = this.s.length ;
        for( i = 0 ; i < len ; i++ ) {
        	if( i % 2 == 0 ) {
        		this.arr[ ( this.s.charCodeAt( i ) - 'a'.charCodeAt( 0 ) ) ]++ ;
        	}
        	else {
        		if( this.arr[ ( this.s.charCodeAt( i ) - 'A'.charCodeAt( 0 ) ) ] > 0 ) {
        			this.arr[ ( this.s.charCodeAt( i ) - 'A'.charCodeAt( 0 ) ) ]-- ;
        		}
        		else {
        			res++ ;
        		}
        	}
        }
        print( res );
    };

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

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

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

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

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.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.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 InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

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

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

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

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

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

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

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

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

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

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

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

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

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

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

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

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

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

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

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

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

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

var cnt = new Array(26);
for(var i=0;i<26;i++)
    cnt[i] = 0;
var n = parseInt(readline());
var s = readline();
var ans = 0;
for(var i=0;i<2*n-2;i+=2) {
    var c = s[i].charCodeAt() - 97;
    cnt[c] ++;
    var c = s[i+1].charCodeAt() - 65;
    if(cnt[c] > 0) cnt[c] --;
    else ans ++;
}
print(ans);

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

let inputString = "";
let currentLine = 0;

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

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

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

  main();
});
// main();

////////////////////////////////////////////////////////////////////////

function main() {
  var a = readline();
  var b = readline().toLocaleLowerCase();
  let counter = 0; //bought keys
  let keys = {}; //key status
  for (let i = 0; i < b.length; i += 2) {
    //first step
    if (keys[b[i]] === undefined) {
      keys[b[i]] = 1;
    } else {
      keys[b[i]]++;
    }
    //second step
    if (keys[b[i + 1]]) {
      keys[b[i + 1]]--;
    } else {
      counter++;
    }
  }
  console.log(counter);
}

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

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , len , len2 ;
        len = this.s.length ;
        res = "" ;
        for( i = 0 ; i < this.n ; i++ ) {
        	this.arr[ i ] = this.arr[ i ] - 1 ;
        }
        this.arr.sort() ;
        for( i = 0 ; i < len ; i++ ) {
        	this.brr[ i ] = this.s.charCodeAt( i ) ;
        }
        j = 0 ;
        cn = 0 ;
        len2 = Math.floor( len / 2 ) ;
        for( i = 0 ; i < len2 ; i++ ) {
        	while( j < this.n && this.arr[ j ] == i ) {
        		cn++ ;
        		j++ ;
        	}
        	if( cn % 2 == 0 ) {
        	}
        	else {
        		temp = this.brr[ i ] ;
        		this.brr[ i ] = this.brr[ len - i - 1 ] ;
        		this.brr[ len - i - 1 ] = temp ;
        	}
        }
        for( i = 0 ; i < len ; i++ ) {
        	res += String.fromCharCode( this.brr[ i ] ) ;
        }
        print( res );
    };

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

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

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

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

    this.declareAndFillArrays = function() {
        var i , j;
        this.srr = new Array();
        this.vis = new Array();
        this.arr = new Array();
        this.brr = new Array();
        this.memo = new Array();
        this.done = new Array();
        this.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.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 InputReader() {
    var self = this ;
    this.allLines = new Array();
    this.currrentLineNumber = 0;
    this.currrentCharacterIndex = 0;
    this.callBackFunction = null ;
    this.parentContext = null ;

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

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

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

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

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

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

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        inputFilePath = currentDirectory + "\\" + inputFileName;
        rawData = fsObj.readFileSync( inputFilePath , "utf8" );
        this.parseRawData( rawData );
    };

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

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

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

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

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

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

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

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

    this.flushOutOutputToFile = function( outputFileName ) {
        var i , sz , res , currentDirectory , fsObj , outputFilePath;
        res = "";
        sz = this.resultantStringArray.length;
        for( i = 0 ; i < sz ; i++ ) {
            if( i != 0 ) {
                res += "\n";
            }
            res += this.resultantStringArray[ i ];
        }
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        outputFilePath = currentDirectory + "\\" + outputFileName;
        fsObj.writeFileSync( outputFilePath , res );
        this.clearPercase();
    };
}

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

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

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

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

    this.configureStreamsAndReadInput();
}

new CodeExecutioner();

var cnt = new Array(26);
for(var i=0;i<26;i++)
    cnt[i] = 0;
var n = parseInt(readline());
var s = readline();
var ans = 0;
for(var i=0;i<2*n-2;i+=2) {
    var c = parseInt(s[i]) - parseInt('a');
    cnt[c] ++;
    var c = parseInt(s[i+1]) - parseInt('A');
    if(cnt[c] > 0) cnt[c] --;
    else ans ++;
}
print(ans);


Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.

The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.

Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order.  It is guaranteed that the solution exists at the given limits.

NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.

var n=+readline();
var ans=[];
for(var i=0;i<n;i++){
	ans.push([]);
}
for(var i=0,j=n*n; i<n*n/2; i++,j--){
	ans[i%n].push(i+1,j);
}
ans.forEach(function(v){
	print(v.join(' '));
});

var n = +readline();
var ans, i = 1, j = Math.pow(n,2);

for(k = 0; k < n; k++){
	for(ans = []; ; i++, j--){
		ans.push(i,j);
		if(ans.length == n){
			print(ans.join(" "));
			i++, j--;
			break;
		}
	}
}

;(function () {

	var n = +readline();
	var f1 = n*n;
	var f2 = 1;

	var t;
	for (var i = 0; i < n; i++) {
		t = [];

		while (t.length < n) {
			t.push(f1--);
			t.push(f2++);
		}

		print(t.join(' '));
	}

}).call(this);

;(function () {

	var n = +readline();
	var o = {
		_min: 1,
		_max: n*n,
		max: function () { return this._max--; },
		min: function () { return this._min++; }
	}

	var t;
	for (var i = 0; i < n; i++) {
		t = [];

		while (t.length < n) {
			t.push(o.min());
			t.push(o.max());
		}

		print(t.join(' '));
	}

}).call(this);

// 334A     Пакетики с конфетами

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var out = '';
var n2 = n * n;
var n2_2 = n2 / 2;

for (var i = 1; i <= n; i++) {
    for (var j = i; j <= n2_2; j+=n) {
        out += j.toString() + ' ' + (n2-j+1).toString() + ' ';
    };
    out += '\n';
};

print(out);

var n = +readline();

for(var i = 1, j = Math.pow(n,2); i <= n; i++, j--){
	write(i + " " + j + "\n");
}

;(function () {

	var n = +readline();
	var s = (1 + n*n)*n/2;
	var o = {
		max: function () {
			for (var i = n*n; i > 0; i--)
				if (!(this[i])) {
					this[i] = true;
					return i;
				}
		}
	}

	var t, sum;
	for (var i = 0; i < n; i++) {
		sum = o.max();
		t = [sum];
		d = sum;

		while (sum != s) {
			--d;
			if (!o[d] && (sum + d) <= s) {
				o[d] = true;
				sum += d;
				t.push(d);
			}
		}

		print(t.join(' '));
	}

}).call(this);

// 334A     Пакетики с конфетами

var n = parseInt(readline());
//var input_line = readline().split(' ').map(Number);
//var n =  input_line[0];
//var m =  input_line[1];

var out = '';
var n2 = n * n;
var n2_2 = n2 / 2;

for (var i = 1; i <= n; i++) {
    for (var j = i; j <= n2_2; j+=n) {
        out += j.toString() + ' ' + (n-j+1).toString() + ' ';
    };
    out += '\n';
};

print(out);


There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to n where n is the total number of messages in the chat.Each message might contain a link to an earlier message which it is a reply to. When opening a message x or getting a link to it, the dialogue is shown in such a way that k previous messages, message x and k next messages are visible (with respect to message x). In case there are less than k messages somewhere, they are yet all shown.Digging deep into your message history, you always read all visible messages and then go by the link in the current message x (if there is one) and continue reading in the same manner.Determine the number of messages you'll read if your start from message number t for all t from 1 to n. Calculate these numbers independently. If you start with message x, the initial configuration is x itself, k previous and k next messages. Messages read multiple times are considered as one.

The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n) — the total amount of messages and the number of previous and next messages visible. The second line features a sequence of integers a1, a2, ..., an (0 ≤ ai < i), where ai denotes the i-th message link destination or zero, if there's no link from i. All messages are listed in chronological order. It's guaranteed that the link from message x goes to message with number strictly less than x.

Print n integers with i-th denoting the number of distinct messages you can read starting from message i and traversing the links while possible.

NoteConsider i = 6 in sample case one. You will read message 6, then 2, then 1 and then there will be no link to go.In the second sample case i = 6 gives you messages 5, 6, 7 since k = 1, then 4, 5, 6, then 2, 3, 4 and then the link sequence breaks. The number of distinct messages here is equal to 6.

function getBeforeStep (i, k) {
  return i < k ? i : k;
}

function getAfterStep (i, k, n) {
  return i + k >= n ? (n - i) - 1 : k;
}

function getStep (i, k, n) {
  return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, lastValue, start, end, prevEnd, step;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;

  start = Math.max(i - k, 0);
  end = i + getAfterStep(i, k, n);
  prevEnd = value + getAfterStep(value, k, n);

  step = i != 0 && value >= 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);

  messages[i] = lastValue + step
}

print(messages.join(' '))

var input = readline().split(' ');
var n = +input[0];
var k = +input[1];
var refs = readline().split(' ').map(function (msg) {
  return +msg;
});
// const n = 20;
// const k = 1;
// const refs = [0, 1, 0, 3, 4, 5, 2, 3, 7, 0, 0, 7, 0, 3, 4, 12, 2, 3, 7, 0];

// Solution
function isRange(arr) {
  return Array.isArray(arr) && typeof arr[0] === 'number';
}

function checkCrossing(arr1, arr2) {
  if (arr1[1] >= arr2[0] && arr1[1] <= arr2[1]) {
    return 'left';
  }
  if (arr1[0] >= arr2[0] && arr1[0] <= arr2[1]) {
    return 'right'
  }
  return 'no';
}

function concatRanges(arr1, arr2) {
  return [
    arr1[0],
    arr2[1]
  ];
}

function getMessages(i) {
  if (refs[i] === 0) {
    return cache[i]; // Get numbers from cache
  }
  var refRange = getMessages(refs[i] - 1);

  // If refRange is like [2, 15]
  if (isRange(refRange)) {
    switch (checkCrossing(refRange, cache[i])) {
      case 'left':
        return concatRanges(refRange, cache[i]);
      case 'right':
        return concatRanges(cache[i], refRange);
      case 'no':
        if (cache[i][0] < refRange[0]) {
          return [cache[i], refRange];
        }
        return [refRange, cache[i]];
    }
  }

  // If refRange kinda [[1, 15], [18, 25]]
  var hasCrossing = false;
  var stopCheck = false;

  for (var k = 0, l = refRange.length; k < l; k++) {
    switch (checkCrossing(refRange[k], cache[i])) {
      case 'left':
        hasCrossing = true;
        refRange[k] = concatRanges(refRange[k], cache[i]);
        break;
      case 'right':
        hasCrossing = true;
        refRange[k] = concatRanges(cache[i], refRange[k]);
        break;
      case 'no':
        // To prevent excess entries
        if (cache[i][1] < refRange[k][0]) {
          stopCheck = true;
        }
        break;
    }
    if (hasCrossing || stopCheck) {
      break;
    }
  }

  if (!hasCrossing) {
    refRange.push(cache[i]);
  }
  return refRange;
}

var res = [];
var cache = [];

for (var ref = 0; ref < n; ref++) {
  cache[ref] = [
    ref - k < 0 ? 0 : ref - k, // Left border
    ref + k >= n ? n - 1 : ref + k // Right border
  ];
}

refs.forEach(function (ref, i) {
  var borders = getMessages(i);

  if (isRange(borders)) {
    res.push(borders[1] - borders[0] + 1);
  } else {
    var sum = 0;

    borders.forEach(function (border) {
      sum += border[1] - border[0] + 1;
    });
    res.push(sum);
  }
});

print(res.join(' '));

var numbers = readline().split(" ").map(function(x) { return parseInt(x); });
var messageHistory = readline().split(" ").map(function(x) { return parseInt(x); });
var visibleMessages = [], N = numbers[0], K = numbers[1];

for(var t = 0; t < N; t++) {
    var maxNumOfUniqueMessages = Math.min(N,
        Math.min(K, t) + 1 + Math.min(K, N - t - 1)
    );

    if(t <= K) {
        visibleMessages[t] = Math.min(
            t + 1 + K,
            maxNumOfUniqueMessages
        );
    } else {
        var linkToPrevMessage = messageHistory[t] - 1;
        var intersectionNumber = (Math.min(linkToPrevMessage + K + 1, N) - (t - K));
        intersectionNumber = intersectionNumber > 0 ? intersectionNumber : 0;

        visibleMessages[t] = linkToPrevMessage >= 0 ?
            visibleMessages[linkToPrevMessage] +
            (maxNumOfUniqueMessages - intersectionNumber):
            maxNumOfUniqueMessages;
   }
}

write(visibleMessages.join(' '));

function getStep (i, k, n) {
  var before = k;
  var after = k;
  if (i < k) {
    before = +(0 - i);
  }
  if (i + k >= n) {
    after = (n - i) - 1;
  }

  return before + after + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, lastValue, step, diff, value;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;
  step = getStep(i, k, n);
  diff = i - value - 1;

  if (value >= 0 && k > 0 && diff < step) {
    step = i - value + k - 1
  }
  messages[i] = lastValue + step
}

print(messages.join(' '))

function getIndexesRange (index, k, arr) {
  var range = [];
  var start =  Math.max(index - k, 0);
  var end = Math.min(index + k + 1, arr.length);
  for (var i = start; i < end ; i++) {
    range.push(i);
  }
  return range;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, range, prevIndex, readedMessages;
var map = {};
var messagesCounts = [];

for (i = 0; i < n; i++) {
  value = messages[i] = parseInt(messages[i]);
  readedMessages = [];

  prevIndex = value - 1;
  if (prevIndex > 0) {
    readedMessages = readedMessages.concat(map[prevIndex]);
  }

  range = getIndexesRange(i, k, messages);

  range.forEach(function (v) {
    if (readedMessages.indexOf(v) == -1) {
      readedMessages.push(v);
    }
  })

  map[i] = readedMessages;
  messagesCounts.push(readedMessages.length);
}

print(messagesCounts.join(' '))

function getBeforeStep (i, k) {
  return i < k ? +(0 - i) : k;
}

function getAfterStep (i, k, n) {
  return i + k >= n ? (n - i) - 1 : k;
}

function getStep (i, k, n) {
  return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, lastValue, start, end, prevEnd, step;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;

  start = Math.max(i - k, 0);
  end = i + getAfterStep(i, k, n);
  prevEnd = value + getAfterStep(value, k, n);

  step = i != 0 && value >= 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);

  messages[i] = lastValue + step
}

print(messages.join(' '))

function getBeforeStep (i, k) {
  return i < k ? +(0 - i) : k;
}

function getAfterStep (i, k, n) {
  return i + k >= n ? (n - i) - 1 : k;
}

function getStep (i, k, n) {
  return getBeforeStep(i, k) + getAfterStep(i, k, n) + 1;
}

var input = readline();
var messages = readline().split(' ');

input = input.split(' ');
var n = parseInt(input[0]);
var k = parseInt(input[1]);

var i, value, lastValue, start, end, prevEnd, step;

for (i = 0; i < n; i++) {
  value = parseInt(messages[i]) - 1;
  lastValue = messages[value] || 0;

  start = i - getBeforeStep(i, k);
  end = i + getAfterStep(i, k, n);
  prevEnd = value + getAfterStep(value, k, n);

  step = i != 0 && start <= prevEnd ? end - prevEnd : getStep(i, k, n);

  messages[i] = lastValue + step
}

print(messages.join(' '))


You are given two arrays of length $$$n$$$: $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$.You can perform the following operation any number of times:   Choose integer index $$$i$$$ ($$$1 \le i \le n$$$);  Swap $$$a_i$$$ and $$$b_i$$$. What is the minimum possible sum $$$|a_1 - a_2| + |a_2 - a_3| + \dots + |a_{n-1} - a_n|$$$ $$$+$$$ $$$|b_1 - b_2| + |b_2 - b_3| + \dots + |b_{n-1} - b_n|$$$ (in other words, $$$\sum\limits_{i=1}^{n - 1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$) you can achieve after performing several (possibly, zero) operations?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 4000$$$) — the number of test cases. Then, $$$t$$$ test cases follow. The first line of each test case contains the single integer $$$n$$$ ($$$2 \le n \le 25$$$) — the length of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — the array $$$b$$$.

For each test case, print one integer — the minimum possible sum $$$\sum\limits_{i=1}^{n-1}{\left(|a_i - a_{i+1}| + |b_i - b_{i+1}|\right)}$$$.

NoteIn the first test case, we can, for example, swap $$$a_3$$$ with $$$b_3$$$ and $$$a_4$$$ with $$$b_4$$$. We'll get arrays $$$a = [3, 3, 3, 3]$$$ and $$$b = [10, 10, 10, 10]$$$ with sum $$$3 \cdot |3 - 3| + 3 \cdot |10 - 10| = 0$$$.In the second test case, arrays already have minimum sum (described above) equal to $$$|1 - 2| + \dots + |4 - 5| + |6 - 7| + \dots + |9 - 10|$$$ $$$= 4 + 4 = 8$$$.In the third test case, we can, for example, swap $$$a_5$$$ and $$$b_5$$$.

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

let s = "";

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

process.stdin.on("end", (data) => {
  s = s.split("\n").filter(Boolean);

  main();
});

function main() {
  const t = Number(s[0]);

  let i = 1;
  while (i < 3 * t + 1) {
    const length = s[i++];
    const a = s[i++].split(" ").map(Number);
    const b = s[i++].split(" ").map(Number);

    solve(a, b);
  }
}

function solve(a, b) {
  function recurse(a, b, index) {
    if (index > a.length - 1) {
      return;
    }

    if (a[index] < b[index]) {
      swap(a, b, index);
    }

    recurse(a, b, index + 1);
  }

  recurse(a, b, 0, 0);
  console.log(doSum(a, b));
}

function swap(a, b, index) {
  const temp = a[index];
  a[index] = b[index];
  b[index] = temp;
}

function doSum(a, b) {
  let sum = 0;
  for (let i = 0; i < a.length - 1; i++) {
    sum += Math.abs(a[i] - a[i + 1]);
    sum += Math.abs(b[i] - b[i + 1]);
  }
  return sum;
}

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

module.exports = E;

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

const MOD = 1e9+7;

const calc = (a, b, n)=>{
  let swap = (i)=>{
    let tmp = a[i];
    a[i] = b[i];
    b[i] = tmp;
  }
  let sum = 0;
  for (let i=1; i<n; i++){
    let v1 = Math.abs(a[i]-a[i-1])+Math.abs(b[i-1]-b[i]);
    let v2 = Math.abs(a[i]-b[i-1])+Math.abs(a[i-1]-b[i]);
    sum += Math.min(v1, v2)
  }
  return sum;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let a = ra();
      let b = ra();
      l('ans')
      print(calc(a, b, n));
    }
}

E.calc = calc;

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);
        let brr = readline().split(' ').map(Number);

        const calc = i => Math.abs(arr[i-1] - arr[i]) + Math.abs(brr[i-1] - brr[i]);

        let sum = 0;
        for (let i = 1; i < n; i++) {
            let cur = calc(i);
            let alt = Math.abs(arr[i-1] - brr[i]) + Math.abs(brr[i-1] - arr[i]);
            if (alt < cur) [arr[i], brr[i]] = [brr[i], arr[i]];
            sum += Math.min(alt, cur);
        }

        output(sum);
    }
}

const readline = require('readline')

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

function solve(n, a, b) {
    for (let i = 0; i < a.length; i++) {
        if (a[i] > b[i]) {
            [a[i], b[i]] = [b[i], a[i]]
        }
    }
    let ans = 0
    for (let i = 1; i < a.length; i++) {
        ans += Math.abs(a[i] - a[i - 1])
        ans += Math.abs(b[i] - b[i - 1])
    }
    // console.log(a, b)
    return ans
}

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

let ls = [];

function solve() {
    let l = 0;
    const t = parseInt(ls[l++]);
    for (let i = 0; i < t; i++) {
        const n = parseInt(ls[l++]);
        const a = ls[l++].split(' ').map(v => parseInt(v));
        const b = ls[l++].split(' ').map(v => parseInt(v));
        solveInner(n, a, b);
    }
}

function solveInner(n, a, b) {
    for (let i = 0; i < n - 1; i++) {
        const d1 = Math.abs(a[i] - a[i + 1]) + Math.abs(b[i] - b[i + 1]);
        const d2 = Math.abs(a[i] - b[i + 1]) + Math.abs(b[i] - a[i + 1]);
        if (d1 > d2) {
            [a[i + 1], b[i + 1]] = [b[i + 1], a[i + 1]];
        }
    }
    let sum = 0;
    for (let i = 0; i < n - 1; i++) {
        sum += Math.abs(a[i] - a[i + 1]);
        sum += Math.abs(b[i] - b[i + 1]);
    }
    console.log(sum);
}

rl.on('line', (l) => ls.push(l));
rl.on('close', () => solve());

const fs = require('fs')
const inputs = fs.readFileSync(0, 'utf-8').split('\n')

function solve(n, a, b) {
  const dp = new Array(n).fill(0).map(() => [0, 0])
  for (let i = 1; i < n; i++) {
    dp[i][0] = Math.min(
      dp[i - 1][0] + Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]),
      dp[i - 1][1] + Math.abs(a[i] - b[i - 1]) + Math.abs(b[i] - a[i - 1]),
    )
    dp[i][1] = Math.min(
      dp[i - 1][0] + Math.abs(b[i] - a[i - 1]) + Math.abs(a[i] - b[i - 1]),
      dp[i - 1][1] + Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]),
    )
  }
  return Math.min(dp[n - 1][0], dp[n - 1][1])
}

void (function main() {
  const _ = Number(inputs[0])
  let res = []

  for (let __ = 0; __ < _; __++) {
    let n = Number(inputs[__ * 3 + 1])
    const a = inputs[__ * 3 + 2].trim().split(' ').map(Number)
    const b = inputs[__ * 3 + 3].trim().split(' ').map(Number)

    res.push(solve(n, a, b))
  }

  console.log(res.join('\n'))
})()

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

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

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

const calc = (n, a, b)=>{
    let res = 0;
    for (let i = 1; i < n; i++) {
        let min = Math.abs(a[i] - a[i - 1]) + Math.abs(b[i] - b[i - 1]);
        min = Math.min(min, Math.abs(a[i] - b[i - 1]) + Math.abs(b[i] - a[i - 1]));
        res += min;
    }
    return res;
};

function main() {
    let T = +readline();
    for (let t = 1; t <= T; t++){
        let n = +readline();
        let a = ra();
        let b = ra();
        console.log(`${calc(n, a, b)}`);
    }
}

var t = +readline()

for(var i = 0; i< t; i ++) {
    var a = readline()
    var arr1 = readline().split(" ").map(x => +x);
    var arr2 = readline().split(" ").map(x => +x);
    print(getMinSum(arr1,arr2))
}

 function getMinSum(arr1,arr2){

    var ai = arr1[0];
    var bi = arr2[0];
    var sum = 0;
    for(var i = 1; i<arr1.length;i++){
        var s1 = Math.abs(arr1[i]-ai)+Math.abs(arr2[i]-bi);
        var s2 = Math.abs(arr2[i]-ai)+Math.abs(arr1[i]-bi);
        if (s1 > s2){
            sum += s2;
            ai = arr2[i];
            bi = arr1[i];
        }else {
            sum += s1;
            ai = arr1[i];
            bi = arr2[i];
        }
    }
    return sum;

}

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

let s = "";

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

process.stdin.on("end", (data) => {
  s = s.split("\n").filter(Boolean);

  main();
});

function main() {
  const t = Number(s[0]);

  let i = 1;
  while (i < 3 * t + 1) {
    const length = s[i++];
    const a = s[i++].split(" ").map(Number);
    const b = s[i++].split(" ").map(Number);

    solve(a, b);
  }
}

function solve(a, b) {
  function recurse(a, b, index) {
    if (index >= a.length - 1) {
      return;
    }

    if (a[index] < b[index]) {
      swap(a, b, index);
    }

    recurse(a, b, index + 1);
  }

  recurse(a, b, 0, 0);
  console.log(doSum(a, b));
}

function swap(a, b, index) {
  const temp = a[index];
  a[index] = b[index];
  b[index] = temp;
}

function doSum(a, b) {
  let sum = 0;
  for (let i = 0; i < a.length - 1; i++) {
    sum += Math.abs(a[i] - a[i + 1]);
    sum += Math.abs(b[i] - b[i + 1]);
  }
  return sum;
}

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

module.exports = E;

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

const MOD = 1e9+7;

const calc = (a, b, n)=>{
  let swap = (i)=>{
    let tmp = a[i];
    a[i] = b[i];
    b[i] = tmp;
  }
  for (let i=1; i<n; i++){
    if (Math.abs(a[i]-a[i-1])>Math.abs(a[i-1]-b[i]))
      swap(i);
  }
  let sum = 0;
  for (let i=1; i<n; i++)
    sum += Math.abs(a[i]-a[i-1])+Math.abs(b[i-1]-b[i])

  return sum;
};

function main() {
    let T = +readline()
    while (T--){
      let [n] = ra();
      let a = ra();
      let b = ra();
      l('ans')
      print(calc(a, b, n));
    }
}

E.calc = calc;


Given an array of integer $$$a_1, a_2, \ldots, a_n$$$. In one operation you can make $$$a_i := a_i + 1$$$ if $$$i < n$$$ and $$$a_i \leq a_{i + 1}$$$, or $$$i = n$$$ and $$$a_i \leq a_1$$$.You need to check whether the array $$$a_1, a_2, \ldots, a_n$$$ can become equal to the array $$$b_1, b_2, \ldots, b_n$$$ in some number of operations (possibly, zero). Two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$ are called equal if $$$a_i = b_i$$$ for all integers $$$i$$$ from $$$1$$$ to $$$n$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 4 \cdot 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) – the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) – the elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, \ldots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) – the elements of the array $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output "YES" if you can get the array $$$b$$$, otherwise output "NO". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

NoteIn the first test case, the array $$$a$$$ is already equal to the array $$$b$$$.In the second test case, we can't get the array $$$b$$$, because to do this we need to decrease $$$a_1$$$.In the fifth test case, we can apply operations in order to the elements with indices $$$4, 3, 3,2,2,2,1,1,1,1$$$, and then get the array $$$[5,5,5,5,5]$$$. After that, you can apply operations in order to elements with indices $$$5,4,4,3,1$$$ and already get an array $$$[6,5,6,7,6]$$$.

"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());
}
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 solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    const helper = (a, b) => {
      for (let i = 0; i < n; i++) {
        if (a[i] > b[i]) return false;
        if (a[i] !== b[i] && b[(i + 1) % n] + 1 < b[i]) return false;
      }
      return true;
    };
    console.log(helper(a, b) ? "YES" : "NO");
  }
};
solve();

'use strict';

var fs = require('fs');

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

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

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

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

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

function output(x) {
    if (typeof x !== 'string') {
        x = x.toString();
    }
    //process.stdout.write(x);   // without auto '\n' (newline)
    console.log(x);  // with auto '\n' (newline)
}

function main() {
    let N = readline();

    for (let test = 0; test < N; test++) {
        let n = parseInt(readline(), 10);
        let arr = readline().split(' ').map(Number);
        let brr = readline().split(' ').map(Number);

        let next = (a, i) => {
            if (i === a.length - 1) {
                return a[0];
            } else {
                return a[i + 1];
            }
        }

        let no = false;
        for (let i = 0; i < n; i++) {
            if (arr[i] === brr[i]) {
                continue;
            }
            if (arr[i] > brr[i]) {
                no = true;
                break;
            }
            if (brr[i] > (next(brr, i) + 1)) {
                no = true;
                break;
            }
        }

        output(no ? 'NO' : 'YES');
    }
}

"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());
}
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 solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    let flag = 1;
    for (let i = 0; i < n; i++) {
      if (a[i] !== b[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 1) {
      console.log("YES");
      continue;
    }
    flag = 1;
    for (let i = 0; i < n; i++) {
      if (b[i] < a[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 0) {
      console.log("NO");
      continue;
    }
    flag = 1;
    let max = a[n - 1];
    for (let i = n - 2; i >= 0; i--) {
      if (a[i] === b[i]) {
        max = a[i];
        continue;
      }
      if (b[i] <= max) {
        a[i] = b[i];
        max = b[i];
        continue;
      } else {
        if (a[i] <= max) a[i] = max;
        else max = a[i];
      }
    }
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) continue;
      if (b[i] - 1 <= a[(i + 1) % n]) a[i] = b[i];
      else {
        flag = 0;
        break;
      }
    }

    if (flag === 0) console.log("NO");
    else console.log("YES");
  }
};
solve();

"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());
}
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 solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    let flag = 1;
    for (let i = 0; i < n; i++) {
      if (a[i] !== b[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 1) {
      console.log("YES");
      continue;
    }
    flag = 1;
    let max = a[n - 1];
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) {
        max = a[i];
        continue;
      }
      if (a[i] < max && b[i] >= max) a[i] = max;
      max = Math.max(max, a[i]);
    }
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) continue;
      if (i === n - 1) {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif2 = a[0] - a[i] + 1;
          if (dif > dif2) {
            flag = 0;
            break;
          } else {
            a[i] = b[i];
          }
        }
      } else {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif1 = a[i + 1] - a[i] + 1;
          if (dif > dif1) {
            flag = 0;
            break;
          } else a[i] = b[i];
        }
      }
    }
    if (flag === 1) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
};
solve();

"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());
}
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 solve = () => {
  let t = getValue();
  while (t--) {
    let n = getValue();
    let a = iInpArr();
    let b = iInpArr();
    let flag = 1;
    for (let i = 0; i < n; i++) {
      if (a[i] !== b[i]) {
        flag = 0;
        break;
      }
    }
    if (flag === 1) {
      console.log("YES");
      continue;
    }
    flag = 1;
    let max = a[n - 1];
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) {
        max = a[i];
        continue;
      }
      if (a[i] < max && b[i] > max) a[i] = max;
      max = Math.max(max, a[i]);
    }
    for (let i = n - 1; i >= 0; i--) {
      if (a[i] === b[i]) continue;
      if (i === n - 1) {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif2 = a[0] - a[i] + 1;
          if (dif > dif2) {
            flag = 0;
            break;
          } else {
            a[i] = b[i];
          }
        }
      } else {
        if (a[i] > b[i]) {
          flag = 0;
          break;
        } else {
          let dif = b[i] - a[i];
          let dif1 = a[i + 1] - a[i] + 1;
          if (dif > dif1) {
            flag = 0;
            break;
          } else a[i] = b[i];
        }
      }
    }
    if (flag === 1) {
      console.log("YES");
    } else {
      console.log("NO");
    }
  }
};
solve();


You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ non-zero integers (i.e. $$$a_i \ne 0$$$). You have to calculate two following values:  the number of pairs of indices $$$(l, r)$$$ $$$(l \le r)$$$ such that $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ is negative;  the number of pairs of indices $$$(l, r)$$$ $$$(l \le r)$$$ such that $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ is positive;

The first line contains one integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^{5})$$$ — the number of elements in the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(-10^{9} \le a_i \le 10^{9}; a_i \neq 0)$$$ — the elements of the sequence.

Print two integers — the number of subsegments with negative product and the number of subsegments with positive product, respectively.

const n = Number(readline());
const a = [1].concat(readline().split(" ").slice(0, n)).map(x => Number(x < 0));
for (var i = 1; i <= n; i++)
  a[i] += a[i - 1];
const counts = [0, 0];
for (var i = 0; i <= n; i++) {
  a[i] &= 1;
  counts[a[i]]++;
}
var negative = 0;
for (var i = 0; i <= n;) {
  var cur = a[i];
  var next = 1 - cur;
  var j = a.indexOf(next, i);
  if (j === -1) break;
  var diff = j - i;
  negative += diff * counts[next];
  counts[cur] -= diff;
  i = j;
}
print(`${negative} ${n * (n + 1) * 0.5 - negative}`);


Vasya is reading a e-book. The file of the book consists of $$$n$$$ pages, numbered from $$$1$$$ to $$$n$$$. The screen is currently displaying the contents of page $$$x$$$, and Vasya wants to read the page $$$y$$$. There are two buttons on the book which allow Vasya to scroll $$$d$$$ pages forwards or backwards (but he cannot scroll outside the book). For example, if the book consists of $$$10$$$ pages, and $$$d = 3$$$, then from the first page Vasya can scroll to the first or to the fourth page by pressing one of the buttons; from the second page — to the first or to the fifth; from the sixth page — to the third or to the ninth; from the eighth — to the fifth or to the tenth.Help Vasya to calculate the minimum number of times he needs to press a button to move to page $$$y$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases. Each testcase is denoted by a line containing four integers $$$n$$$, $$$x$$$, $$$y$$$, $$$d$$$ ($$$1\le n, d \le 10^9$$$, $$$1 \le x, y \le n$$$) — the number of pages, the starting page, the desired page, and the number of pages scrolled by pressing one button, respectively.

Print one line for each test. If Vasya can move from page $$$x$$$ to page $$$y$$$, print the minimum number of times he needs to press a button to do it. Otherwise print $$$-1$$$.

NoteIn the first test case the optimal sequence is: $$$4 \rightarrow 2 \rightarrow 1 \rightarrow 3 \rightarrow 5$$$.In the second test case it is possible to get to pages $$$1$$$ and $$$5$$$.In the third test case the optimal sequence is: $$$4 \rightarrow 7 \rightarrow 10 \rightarrow 13 \rightarrow 16 \rightarrow 19$$$.

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

let l = 0;
let n = 0

rl.on('line', (input) => {
    if (l === 0) {
        n = parseInt(input)
    } else {
        if (l === n)
            rl.close();

        let arr = input.split(" ").map(x => parseInt(x))
        // console.log((arr[1]-1)%arr[3])
        let max = 999999999999
        let ans1 = max
        let ans2 = max
        let ans3 = max
        if (Math.abs(arr[2] - arr[1]) % arr[3] === 0) {
            ans1 = Math.round(Math.abs(arr[2] - arr[1]) / arr[3])
        }
        if (Math.abs(arr[2] - 1) % arr[3] === 0) {
            let rest1 = Math.abs(arr[2] - 1) / arr[3]
            let rest2 = Math.abs(arr[1] - 1) / arr[3]
            ans2 = Math.round(rest1) + Math.ceil(rest2)

        }
        if (Math.abs(arr[0] - arr[2]) % arr[3] === 0) {
            let rest1 = Math.abs(arr[1] - arr[0]) / arr[3]
            let rest2 = Math.abs(arr[0] - arr[2]) / arr[3]
            ans3 = Math.ceil(rest1) + Math.round(rest2)
        }
        //console.log(ans1, ans2, ans3)
        let mn = Math.min(ans1, Math.min(ans2, ans3))
        console.log(mn === max ? -1 : mn)
    }
    l++
});

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print(Math.abs(y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil((x - 1) / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 100000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 100000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }
    }
}

var t = +readline();

for (var i=0; i<t; i++){
	var tn = readline().split(' ').map(Number);
	var n = tn[0];
	var x = tn[1];
	var y = tn[2];
	var d = tn[3];

	if ( Math.abs(y-x)%d == 0 ) print (Math.abs(y-x)/d);
	else if ( (y-1)%d == 0 && (n-y)%d == 0 ) {
		if ( (Math.ceil((x-1)/d) + (y-1)/d) < (Math.ceil((n-x)/d) + (n-y)/d) ) print ((Math.ceil((x-1)/d) + (y-1)/d));
		else print (Math.ceil((n-x)/d) + (n-y)/d);
	} else if ((y-1)%d == 0) print ((Math.ceil((x-1)/d) + (y-1)/d));
	  else if ((n-y)%d == 0) print (Math.ceil((n-x)/d) + (n-y)/d);
	else print (-1);
}

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

let l = 0;
let n = 0

rl.on('line', (input) => {
    if (l === 0) {
        n = parseInt(input)
    } else {
        if (l === n)
            rl.close();

        let arr = input.split(" ").map(x => parseInt(x))
        if (Math.abs(arr[2] - arr[1]) % arr[3] === 0) {
            console.log(Math.floor(Math.abs(arr[2] - arr[1]) / arr[3]))
        } else if (Math.abs(Math.min(arr[2], arr[1]) - 2) % arr[3] === 0 &&
            Math.abs(Math.max(arr[2], arr[1]) - 1) % arr[3] === 0) {
            console.log(Math.floor(Math.max(arr[2], arr[1]) - 1 / arr[3]))
        } else
            console.log("-1")
    }
    l++
});

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print((y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil(x / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 100000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 100000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }

    }
}

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print((y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil(x / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 10000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 10000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }
    }
}

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((y - x) % d === 0) print((y - x) / d);
    else {
        if (((y - 1) % d) !=0 && ((n - y) % d) != 0) print(-1);
        else {
            var diffBeg = Math.ceil((x-1) / d) + ( ((y - 1) % d) ===0 ? (y - 1) / d : 100000000000);
            var diffEnd = Math.ceil((n - x) / d) + ( ((n - y) % d) ===0 ? (n - y) / d : 100000000000);
            print( (diffBeg < diffEnd) ? diffBeg : diffEnd);
        }

    }
}

var t = readline();
for (var i=0; i<t; i++) {
    var input = readline().split(' ');
    var n = input[0];
    var x = input[1];
    var y = input[2];
    var d = input[3];
    if ((x - y) % d === 0) print((x - y) / d);
    else {
        var diffBeg = ((y - 1) % d);
        var diffEnd = ((n - y) % d);
        if (diffBeg != 0 || diffEnd != 0) print(-1);
        else print( (diffBeg < diffEnd) ? (y - 1)/d : (n-y)/d);
    }
}


"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?

First line consists of a single integer n (1 ≤ n ≤ 105) — the number of stewards with Jon Snow. Second line consists of n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) representing the values assigned to the stewards.

Output a single integer representing the number of stewards which Jon will feed.

NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

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

function print(s) {
  process.stdout.write(`${s}`);
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  // input
  const n = +readline();
  let a = readline().split(' ').map(x => parseInt(x));
  let r = 0;
  if (a.length > 2) {
    let min = Number.MAX_SAFE_INTEGER, max = Number.MIN_SAFE_INTEGER;
    for (let i = 0; i < n; i++) {
      min = Math.min(min, a[i]);
      max = Math.max(max, a[i]);
    }
    for (let i = 0; i < n; i++) {
      if (a[i] > min && a[i] < max) {
        r++;
      }
    }
  }
  print(r);
}

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

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

  const arr = d.split(' ').map(Number);
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  let ans = 0;

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > min && arr[i] < max) {
      ans++;
    }
  }

  console.log(ans);

  c++;
});

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}
function main() {
    let [n] = readint();
    let a = readint();
    let all = a.length;
    let mx = a[0];
    let mn = a[0];
    a.forEach(element => {
        if(mx < element) mx = element;
        if(mn > element) mn = element;
    });
    let mxcount = 0,
        mncount = 0;
    a.forEach(element => {
        if(element == mx) mxcount++;
        if(element == mn) mncount++;
    });
    if(mx != mn)
        print(a.length - mncount - mxcount);
    else
        print(a.length - mncount);
}

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  console.log(0);
  return
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min) {
    if (min !== max) {
      result += cmin;
    }
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max) {
    if (min !== max) {
      result += cmax;
    }
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
console.log(result);
});

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;
input.sort((a,b)=>a-b);
var small=input[0];
var big=input[n-1];

for(var i=1;i<=n-2;i++){
    if(input[i]>small && input[i]<big){
        res++;
    }
}

print(res);

function findMin(array){
    var mn = Infinity;
    for(var i=0;i<array.length;i++){
        mn=Math.min(array[i],mn)
    }
    return mn;
}

function findMax(array){
    var mx = -Infinity;
    for(var i=0;i<array.length;i++){
        mx=Math.max(array[i],mx);
    }
    return mx;
}

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;

var mn=findMin(input);
var mx=findMax(input);

for(var i=0;i<n;i++){
    if(input[i]>mn && input[i]<mx){
        res++;
    }
}

print(res);

var n = Number(readline()),
    stewards = readline().split(' ').map(Number).sort((a,b)=>a-b),
    counter = 0;

    big = stewards[stewards.length - 1],
    small = stewards[0];

for (var i = 1; i < stewards.length - 1; i++){

    if(stewards[i] > small && stewards[i] < big)
        counter++;

    // var count = i,
    //     thereIsBefore = false,
    //     thereIsAfter = false;
    // while(count > 0) {
    //     if(stewards[count - 1] < stewards[i]){
    //         thereIsBefore = true;
    //         break;
    //     }
    //     count--;
    // }
    // while(count < stewards.length - 1) {
    //     if(stewards[count + 1] > stewards[i]){
    //         thereIsAfter = true;
    //         break;
    //     }
    //     count++;
    // }
    // if(thereIsAfter && thereIsBefore)
    //     counter++;

}

print(counter);

function main(n,arr){

    var min  = Infinity;
    var max =  -Infinity;
    var cnt = 0;

    for(var i = 0 ; i < n ; i++){

      max = Math.max(max,arr[i]);
      min = Math.min(min,arr[i]);

    }

    for(var i = 0 ; i < n ; i++){
      if(arr[i] > min && arr[i] < max)cnt++;
    }

    print(cnt);
}

var n = parseInt(readline());

var arr = readline().split(' ');
for(var i = 0  ; i < arr.length ; i++)arr[i] = parseInt(arr[i]);

main(n,arr);

var n = parseInt(readline());
var p = readline().split(' ').map(function(x){
    return parseInt(x);
});
var minv = 1e9;
var maxv = -1e9;
p.forEach(function(x){
   minv = Math.min(minv, x);
   maxv = Math.max(maxv, x);
});
print(p.filter(function(x){
    return minv < x && x < maxv;
}).length);

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  stewardsStrength = stewardsStrength.sort((a, b) => a - b)

  var i = 1
  var count = 0
  while (i < numberOfSteward) {
    if (stewardsStrength[0] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[stewardsStrength.length - 1]) {
      count += 1
    }
    i++
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  var weaker = Infinity
  var stronger = -Infinity
  for (var i = 0; i < numberOfSteward; i++) {
    weaker = Math.min(weaker, stewardsStrength[i])
    stronger = Math.max(stronger, stewardsStrength[i])
  }

  var count = 0
  for (var i = 0; i < numberOfSteward; i++) {
    if (weaker < stewardsStrength[i] && stewardsStrength[i] < stronger) {
      count += 1
    }
  }

  print(count)

var n = parseInt(readline())
var list = readline().trim().split(' ')
var min = 1e9+1, max = -1
var dict = {}
var total = list.length
for (var num of list) {
    num = parseInt(num)
    min = min > num ? num : min
    max = max < num ? num : max
    dict[num] = (dict[num] || 0) + 1
}

if (min === max) {
    print(0)
} else {
    print (total - dict[min] - dict[max])
}

var stuartsCount = +readline(),
    stuartsRaits = readline().split(/\s+/).slice(0, stuartsCount),
    minRait = Math.min.apply(null, stuartsRaits),
    maxRait = Math.max.apply(null, stuartsRaits);

print(
    stuartsRaits.reduce(function(count, rait){
        return (rait > minRait && rait < maxRait) ? count + 1 : count;
    }, 0)
);

// Generated by CoffeeScript 1.12.4
(function() {
  var count, max, min, stuarts;

  readline();

  stuarts = readline().split(" ").map(Number);

  min = stuarts[0];

  max = 0;

  count = 0;

  stuarts.forEach(function(num) {
    if (num < min) {
      min = num;
    }
    if (num > max) {
      return max = num;
    }
  });

  stuarts.forEach(function(num) {
    if (num > min && num < max) {
      return count++;
    }
  });

  write(count);

}).call(this);

console = {log: ()=>{}}
var count, max, min, stuarts;
readline();
stuarts = readline().split(" ").map(Number);
min = stuarts[0];
max = 0;
count = 0;
stuarts.forEach(function(num) {
  if (num < min) {
    min = num;
  }
  if (num > max) {
    return max = num;
  }
});
stuarts.forEach(function(num) {
  if (num > min && num < max) {
    return count++;
  }
});
write(count);

try {require("codeforces")} catch(e){console = {log: function(){}, error: function(){}}};

var count, max, min, stuarts;
readline();
stuarts = readline().split(" ").map(Number);
min = stuarts[0];
max = 0;
count = 0;
stuarts.forEach(function(num) {
    if (num < min) {
        min = num;
    }
    if (num > max) {
        return max = num;
    }
});
console.log("ssss");
stuarts.forEach(function(num) {
    if (num > min && num < max) {
        return count++;
    }
});
write(count);

var n = parseInt(readline());
var total = readline().split(" ").map(Number).sort((a, b) => a - b);

var count = total.length - 2;

for (var i = 0; i < total.length; i++) {
    if ((i !== 0 && total[i] === total[0]) ||
        (i !== total.length - 1 && total[i] === total[total.length - 1])) {
        count--;
    }
}

print(count < 0 ? 0: count);

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

    main();
});

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

function readint() {
    let line = readline().split(' ').map(function(num) {
        return parseInt(num);
    });
    return line;
}

function readfloat() {
    let line = readline().split(' ').map(function(num) {
        return parseFloat(num);
    });
    return line;
}

function print(x) {
    console.log(x);
}

function write(x) {
    process.stdout.write(x);
}
function main() {
    let [n] = readint();
    let a = readint();
    let all =a.length;
    let mx = a[0];
    let mn = a[0];
    a.forEach(element => {
        if(mx < element) mx = element;
        if(mn > element) mn = element;
    });
    let mxcount = 0,
        mncount = 0;
    a.forEach(element => {
        if(element == mx) mxcount++;
        if(element == mn) mncount++;
    });
    print(a.length - mncount - mncount);
}

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  console.log(0);
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min && min !== max) {
    result += cmin;
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max && min !== max) {
    result += cmax;
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
console.log(result);
});

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  return 0;
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min && min !== max) {
    result += cmin;
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max && min !== max) {
    result += cmax;
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
return result;
});

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
let input = [];
readline.on('line', line => {
  input.push(line);
});
process.stdin.on('end', () => {
// const n = parseInt(input[0], 10);
let secondLine = input[1].split(' ');
const nums = secondLine.map((a) => parseInt(a, 10));

if (nums.length <= 2) {
  console.log(0);
  return
}

let min = nums[0];
let max  = nums[0];
let cmin = 1;
let cmax = 1;
let result = 0;

for (let i=1; i< nums.length; i++) {
  const num = nums[i];
  const nmin = Math.min(min, num);
  if (nmin !== min && min !== max) {
    result += cmin;
    cmin = 1;
  }
  if (num === min) {
    cmin += 1;
  }
  const nmax = Math.max(max, num);
  if (nmax !== max && min !== max) {
    result += cmax;
    cmax = 1;
  }
  if (num === max) {
    cmax += 1;
  }
  if (nmin === min && nmax === max && nmax !== num && nmin !== num) {
    result += 1;
  }
// console.log({num ,min, nmin, max, nmax, result});
  min = nmin;
  max = nmax;
}
console.log(result);
});

function findMin(array){
    var mn = Infinity;
    for(var i=0;i<array.length;i++){
        mn=Math.min(array[i],mn)
    }
    return mn;
}

function findMax(array){
    var mx = -Infinity;
    for(var i=0;i<array.length;i++){
        mx=Math.max(array[i],mx);
    }
    return mx;
}

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;

var mn=findMin(input);
var mx=findMax(input);

for(var i=1;i<=n-2;i++){
    if(input[i]>mn && input[i]<mx){
        res++;
    }
}

print(res);

var n = parseInt(readline());
var input = readline().split(' ').map(x=>parseInt(x));
var res=0;
input.sort((a,b)=>a-b);
for(var i=1;i<n-1;i++){

    if((input[i-1]<input[i]) && (input[i]<input[i+1])){

        res++;
    }
}

print(res);

var n = Number(readline()),
    stewards = readline().split(' ').map(Number).sort(),
    counter = 0;
for (var i = 1; i < stewards.length - 1; i++){
    var count = i,
        thereIsBefore = false,
        thereIsAfter = false;
    while(count > 0) {
        if(stewards[count - 1] < stewards[i]){
            thereIsBefore = true;
            break;
        }
        count--;
    }
    while(count < stewards.length - 1) {
        if(stewards[count + 1] > stewards[i]){
            thereIsAfter = true;
            break;
        }
        count++;
    }
    if(thereIsAfter && thereIsBefore)
        counter++;

}

print(counter);

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  stewardsStrength = stewardsStrength.sort((a, b) => a - b)

  var i = 1
  var count = 0
  while (i < numberOfSteward - 1) {
    if (stewardsStrength[i - 1] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[i + 1]) {
      count += 1
    }
    i++
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  var weaker = Infinity
  var stronger = -Infinity
  for (var i = 0; i < numberOfSteward; i++) {
    weaker = Math.min(weaker, numberOfSteward[i])
    stronger = Math.max(stronger, numberOfSteward[i])
  }

  var count = 0
  for (var i = 0; i < numberOfSteward; i++) {
    if (stewardsStrength[0] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[stewardsStrength.length - 1]) {
      count += 1
    }
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  var weaker = Infinity
  var stronger = -Infinity
  for (var i = 0; i < numberOfSteward; i++) {
    weaker = Math.min(weaker, numberOfSteward[i])
    stronger = Math.max(stronger, numberOfSteward[i])
  }

  var count = 0
  for (var i = 0; i < numberOfSteward; i++) {
    if (weaker < stewardsStrength[i] && stewardsStrength[i] < stronger) {
      count += 1
    }
  }

  print(count)

var numberOfSteward = Number(readline())
  var stewardsStrength = readline().split(' ').map(Number)

  stewardsStrength = stewardsStrength.sort((a, b) => a - b)

  var i = 1
  var count = 0
  while (i < numberOfSteward - 1) {
    if (stewardsStrength[i - 1] < stewardsStrength[i] && stewardsStrength[i] < stewardsStrength[i + 1]) {
      count += 1
      i += 3
    } else {
      i++
    }
  }

  print(count)

var stuartsCount = +readline(),
    stuartsRaits = readline().split(/\s+/),
    minRait = stuartsRaits[0],
    maxRait = stuartsRaits[0],
    result = 0;

stuartsRaits.forEach(function(rait){
    var tmpRait;

    if(rait > maxRait) {
        tmpRait = maxRait;
        maxRait = rait;
        checkNeedGuard(tmpRait);
        return;
    }

    if(rait < minRait) {
        tmpRait = minRait;
        minRait = rait;
        checkNeedGuard(tmpRait);
        return;
    }

    checkNeedGuard();
});

function checkNeedGuard(rait) {
     if(rait > minRait && rait < maxRait) result++;
}

print(result);

try {require("codeforces")} catch(e){console = {log: function(){}, error: function(){}}};

var count, max, min, stuarts;
readline();
stuarts = readline().split(" ").map(Number);
min = stuarts[0];
max = 0;
count = 0;
stuarts.forEach(function(num) {
    if (num < min) {
        min = num;
    }
    if (num > max) {
        return max = num;
    }
});
console.log("ssss");
stuarts.forEach(function(num) {
    if (num > min && num < max) {
        return count+2;
    }
});
write(count);

var n = parseInt(readline());
var total = readline().split(" ").map(Number).sort((a, b) => a - b);

var se = new Set(total);

if (se.size <= 2) {
    print(0);
} else {
    print(se.size - 2);
}

var n = parseInt(readline());
var total = readline().split(" ").map(Number).sort((a, b) => a - b);

var count = total.length - 2;

for (var i = 0; i < total.length; i++) {
    if (total[i] === total[0] || total[i] === total[total.length - 1]) {
        count--;
    }
}

print(count < 0 ? 0: count);