An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.

The single line of the input contains integer k (1 ≤ k ≤ 100) — the required degree of the vertices of the regular graph.

Print "NO" (without quotes), if such graph doesn't exist.  Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines. The description of the made graph must start with numbers n and m — the number of vertices and edges respectively.  Each of the next m lines must contain two integers, a and b (1 ≤ a, b ≤ n, a ≠ b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order. The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).

NoteIn the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.

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.resetArr = function() {
    	var i ;
    	for( i = 0 ; i < this.lim1 ; i++ ) {
        	this.arr[ i ] = 0 ;
        }
    } ;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , nodes , edges , fl , mi , ma , x , y ;
        res = 0 ;
        this.arr = [] ;
        this.resetArr() ;
        if( this.n % 2 == 0 ) {
        	print( "NO" );
        }
        else if( this.n == 1 ) {
        	print( "YES" );
        	print( "2 1" );
        	print( "1 2" );
        }
        else {
        	print( "YES" );
        	a = this.n + 2 ;
        	nodes = 2 * a ;
        	this.brr = [] ;
        	this.brr.push( { u : 1 , v : a + 1 } ) ;
        	this.resetArr() ;
        	this.arr[ 1 ]++ ;
        	while( true ) {
        		fl = 1 ;
        		for( i = 1 ; i <= a ; i++ ) {
        			if( this.arr[ i ] != this.n ) {
        				fl = 0 ;
        				break ;
        			}
        		}
        		if( fl == 1 ) {
        			break ;
        		}
        		ma = -1 ;
        		mi = 1000000000 ;
        		for( i = 1 ; i <= a ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] < mi ) {
        				mi = this.arr[ i ] ;
        				x = i ;
        			}
        		}
        		for( i = 1 ; i <= a ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] > ma && i != x ) {
        				ma = this.arr[ i ] ;
        				y = i ;
        			}
        		}
        		this.arr[ x ]++ ;
        		this.arr[ y ]++ ;
        		this.brr.push( { u : Math.min( x , y ) , v : Math.max( x , y ) } ) ;
        	}
        	this.resetArr() ;
        	this.arr[ a + 1 ]++ ;
        	while( true ) {
        		fl = 1 ;
        		for( i = a + 1 ; i <= a * 2 ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] != this.n ) {
        				fl = 0 ;
        				break ;
        			}
        		}
        		if( fl == 1 ) {
        			break ;
        		}
        		ma = -1 ;
        		mi = 1000000000 ;
        		for( i = a + 1 ; i <= a * 2 ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] < mi ) {
        				mi = this.arr[ i ] ;
        				x = i ;
        			}
        		}
        		for( i = a + 1 ; i <= a * 2 ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] > ma && i != x ) {
        				ma = this.arr[ i ] ;
        				y = i ;
        			}
        		}
        		this.arr[ x ]++ ;
        		this.arr[ y ]++ ;
        		this.brr.push( { u : Math.min( x , y ) , v : Math.max( x , y ) } ) ;
        	}
	        edges = this.brr.length ;
        	print( nodes + ' ' + edges ) ;
        	for( i = 0 ; i < edges ; i++ ) {
        		print( this.brr[ i ].u + ' ' + this.brr[ i ].v ) ;
        	}
        }
    };

    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.n = irObj.nextInt();
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

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

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

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

    this.init();
}

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

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

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

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

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

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

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

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        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();

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.resetArr = function() {
    	var i ;
    	for( i = 0 ; i < this.lim1 ; i++ ) {
        	this.arr[ i ] = 0 ;
        }
    } ;

    this.solveCase = function() {
        var res , i , j , fl , cn , temp , nodes , edges , fl , mi , ma , x , y ;
        res = 0 ;
        this.arr = [] ;
        this.resetArr() ;
        if( this.n % 2 == 0 ) {
        	print( "NO" );
        }
        else if( this.n == 1 ) {
        	print( "YES" );
        	print( "2 1" );
        	print( "1 2" );
        }
        else {
        	print( "YES" );
        	a = this.n + 2 ;
        	nodes = 2 * a ;
        	this.brr = [] ;
        	this.brr.push( { u : 1 , v : this.n + 1 } ) ;
        	this.resetArr() ;
        	this.arr[ 1 ]++ ;
        	while( true ) {
        		fl = 1 ;
        		for( i = 1 ; i <= a ; i++ ) {
        			if( this.arr[ i ] != this.n ) {
        				fl = 0 ;
        				break ;
        			}
        		}
        		if( fl == 1 ) {
        			break ;
        		}
        		ma = -1 ;
        		mi = 1000000000 ;
        		for( i = 1 ; i <= a ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] < mi ) {
        				mi = this.arr[ i ] ;
        				x = i ;
        			}
        		}
        		for( i = 1 ; i <= a ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] > ma && i != x ) {
        				ma = this.arr[ i ] ;
        				y = i ;
        			}
        		}
        		this.arr[ x ]++ ;
        		this.arr[ y ]++ ;
        		this.brr.push( { u : x , v : y } ) ;
        	}
        	this.resetArr() ;
        	this.arr[ a + 1 ]++ ;
        	while( true ) {
        		fl = 1 ;
        		for( i = a + 1 ; i <= a * 2 ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] != this.n ) {
        				fl = 0 ;
        				break ;
        			}
        		}
        		if( fl == 1 ) {
        			break ;
        		}
        		ma = -1 ;
        		mi = 1000000000 ;
        		for( i = a + 1 ; i <= a * 2 ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] < mi ) {
        				mi = this.arr[ i ] ;
        				x = i ;
        			}
        		}
        		for( i = a + 1 ; i <= a * 2 ; i++ ) {
        			if( this.arr[ i ] < this.n && this.arr[ i ] > ma && i != x ) {
        				ma = this.arr[ i ] ;
        				y = i ;
        			}
        		}
        		this.arr[ x ]++ ;
        		this.arr[ y ]++ ;
        		this.brr.push( { u : x , v : y } ) ;
        	}
	        edges = this.brr.length ;
        	print( nodes + ' ' + edges ) ;
        	for( i = 0 ; i < edges ; i++ ) {
        		print( this.brr[ i ].u + ' ' + this.brr[ i ].v ) ;
        	}
        }
    };

    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.n = irObj.nextInt();
        }
        catch( ex ) {
            hasMoreInput = false;
        }
        return hasMoreInput;
    };

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

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

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

    this.init();
}

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

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

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

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

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

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

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

    this.readAllLinesFromFile = function( inputFileName ) {
        var currentDirectory , fsObj , inputFilePath , rawData;
        fsObj = require( 'fs' );
        currentDirectory = __dirname;
        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();


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation.

NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$.

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ');
    reverse(datas, n);
}

function reverse(data, n) {
	var l = -1, r = 0;
	var i;
	for (i = 0; i < n; i++) {
	    data[i] = parseInt(data[i])
	    if (data[i] == l+1) {
	        r = i;
	        break;
	    }
	    if (data[i] != i+1 && l == -1) {
	        l = i;
	    }
	}
	var res = '';
	l = l == -1 ? 0 : l;
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ').map((x) => parseInt(x));
    reverse(datas, n);
}

function reverse(data, n) {
	var l = 0, r = 0, max = -1, min = 0;
	var i;
    if (data[0] != 1) max = 0;
	for (i = 1; i < n; i++) {
	    if ((min === 0 && data[i] < data[max]) || data[i] < data[min]){
			min = i;
			r = i;
		}
		if (max === -1 && data[i] > data[i - 1] + 1 && min === 0) {
			max = i;
			l = i;
		}
	}
	var res = '';
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var caseMap = new Map();
    for (var j = 0; j < caseLength; j++)
    {
        caseMap[caseArray[j]] = j;
    }
    var start = 0;
    var flag = false;
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (caseArray[j] !== `${j+1}`)
        {
            var startRevIndex = caseMap[`${j+1}`];
            if (startRevIndex !== null)
            {
                for (var k = startRevIndex; k >= j; k--)
                {
                    result += `${caseArray[k]} `;
                }
                start = startRevIndex + 1;
                flag = true;
                break;
            }
        }
        else result += `${caseArray[j]} `;
    }
    if (flag)
    {
        for (var j = start; j < caseLength; j++)
        {
            result += `${caseArray[j]} `;
        }
    }
    print(result);
}

var tests = parseInt(readline());

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

  for (var j = 0; j < arr.length && arr[j] == j + 1; j++) {}
  if (j != arr.length) {
    l = j;
    for (var j = l; j < arr.length && arr[j] != l + 1; j++) {}
    r = j;
    for (var j = l; j < r; j++) {
      var tmp = arr[j];
      arr[j] = arr[r];
      arr[r--] = tmp;
    }
  }
  print(arr.join(" "));
}

// problems/contest1638/A/src/ts/solution.ts
var lines = [];
require("readline").createInterface({
  input: process.stdin
}).on("line", (line) => lines.push(line));
process.stdin.on("end", () => {
  main(lines);
});
function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]];
}
function reverse(arr, i, j) {
  while (i < j)
    swap(arr, i++, j--);
}
function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1;
      while (j < n && nums[j] !== i + 1)
        j++;
      reverse(nums, i, j);
      break;
    }
  }
  return nums;
}
function main(lines2) {
  let ln = 0;
  let t = Number(lines2[ln++]);
  for (; t; t--) {
    const n = Number(lines2[ln++]);
    const nums = lines2[ln++].split(" ").map(Number);
    output(solve(n, nums));
  }
}
function output(res) {
  console.log(res.map((x) => `${x} `).join(""));
}

// problems/lib/js/array.js
function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]];
}
function reverse(arr, i, j) {
  while (i < j)
    swap(arr, i++, j--);
}

// problems/contest1638/A/src/js/solution.js
var lines = [];
require("readline").createInterface({
  input: process.stdin
}).on("line", (line) => lines.push(line));
process.stdin.on("end", () => {
  main(lines);
});
function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1;
      while (j < n && nums[j] !== i + 1)
        j++;
      reverse(nums, i, j);
      break;
    }
  }
  return nums;
}
function main(lines2) {
  let ln = 0;
  let t = Number(lines2[ln++]);
  for (; t; t--) {
    const n = Number(lines2[ln++]);
    const nums = lines2[ln++].split(" ").map(Number);
    output(solve(n, nums));
  }
}
function output(res) {
  console.log(res.map((x) => `${x} `).join(""));
}

/*
A. Reverse
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a permutation p1,p2,…,pn of length n. You have to choose two integers l,r (1≤l≤r≤n)
and reverse the subsegment [l,r] of the permutation. The permutation will become
p1,p2,…,pl−1,pr,pr−1,…,pl,pr+1,pr+2,…,pn.

Find the lexicographically smallest permutation that can be obtained by performing exactly one
reverse operation on the initial permutation.

Note that for two distinct permutations of equal length a and b, a is lexicographically smaller than
b if at the first position they differ, a has the smaller element.

A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For
example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the
array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).

Input

Each test contains multiple test cases. The first line contains a single integer t (1≤t≤500) — the
number of test cases. Description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤500) — the length of the
permutation.

The second line of each test case contains n integers p1,p2,…,pn (1≤pi≤n) — the elements of the
permutation.

Output

For each test case print the lexicographically smallest permutation you can obtain.

Example
Input
Copy

4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5

Output
Copy

1
1 2 3
1 2 4 3
1 2 3 4 5

Note

In the first test case, the permutation has length 1, so the only possible segment is [1,1]. The
resulting permutation is [1].

In the second test case, we can obtain the identity permutation by reversing the segment [1,2]. The
resulting permutation is [1,2,3].

In the third test case, the best possible segment is [2,3]. The resulting permutation is [1,2,4,3].

In the fourth test case, there is no lexicographically smaller permutation, so we can leave it
unchanged by choosing the segment [1,1]. The resulting permutation is [1,2,3,4,5].
*/

const lines = []

require('readline').createInterface({
  input: process.stdin
}).on('line', line => lines.push(line))

process.stdin.on('end', () => {
  main(lines)
})

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]]
}

function reverse(arr, i, j) {
  while (i < j) swap(arr, i++, j--)
}

function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1
      while (j < n && nums[j] !== i + 1) j++
      reverse(nums, i, j)
      break
    }
  }
  return nums
}

function main(lines) {
  let ln = 0
  let t = Number(lines[ln++])
  const res = []
  for (; t; t--) {
    const n = Number(lines[ln++])
    const nums = lines[ln++].split(' ').map(Number)
    output(solve(n, nums))
  }
}

function output(res) {
  console.log(res.map(x => `${x} `).join(''))
}

/*
A. Reverse
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a permutation p1,p2,…,pn of length n. You have to choose two integers l,r (1≤l≤r≤n)
and reverse the subsegment [l,r] of the permutation. The permutation will become
p1,p2,…,pl−1,pr,pr−1,…,pl,pr+1,pr+2,…,pn.

Find the lexicographically smallest permutation that can be obtained by performing exactly one
reverse operation on the initial permutation.

Note that for two distinct permutations of equal length a and b, a is lexicographically smaller than
b if at the first position they differ, a has the smaller element.

A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For
example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the
array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).

Input

Each test contains multiple test cases. The first line contains a single integer t (1≤t≤500) — the
number of test cases. Description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤500) — the length of the
permutation.

The second line of each test case contains n integers p1,p2,…,pn (1≤pi≤n) — the elements of the
permutation.

Output

For each test case print the lexicographically smallest permutation you can obtain.

Example
Input
Copy

4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5

Output
Copy

1
1 2 3
1 2 4 3
1 2 3 4 5

Note

In the first test case, the permutation has length 1, so the only possible segment is [1,1]. The
resulting permutation is [1].

In the second test case, we can obtain the identity permutation by reversing the segment [1,2]. The
resulting permutation is [1,2,3].

In the third test case, the best possible segment is [2,3]. The resulting permutation is [1,2,4,3].

In the fourth test case, there is no lexicographically smaller permutation, so we can leave it
unchanged by choosing the segment [1,1]. The resulting permutation is [1,2,3,4,5].
*/

const lines = []

require('readline').createInterface({
  input: process.stdin
}).on('line', line => lines.push(line))

process.stdin.on('end', () => {
  output(main(lines))
})

function output(res) {
  for (const r of res) {
    console.log(r.join(' '))
  }
}

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]]
}

function reverse(arr, i, j) {
  while (i < j) swap(arr, i++, j--)
}

function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1
      while (j < n && nums[j] !== i + 1) j++
      reverse(nums, i, j)
      break
    }
  }
  return nums
}

function main(lines) {
  let l = 0
  let t = Number(lines[l++])
  const res = []
  for (; t; t--) {
    const n = Number(lines[l++])
    const nums = lines[l++].split(' ').map(Number)
    res.push(solve(n, nums))
  }
  return res
}

/*
A. Reverse
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a permutation p1,p2,…,pn of length n. You have to choose two integers l,r (1≤l≤r≤n)
and reverse the subsegment [l,r] of the permutation. The permutation will become
p1,p2,…,pl−1,pr,pr−1,…,pl,pr+1,pr+2,…,pn.

Find the lexicographically smallest permutation that can be obtained by performing exactly one
reverse operation on the initial permutation.

Note that for two distinct permutations of equal length a and b, a is lexicographically smaller than
b if at the first position they differ, a has the smaller element.

A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For
example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the
array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).

Input

Each test contains multiple test cases. The first line contains a single integer t (1≤t≤500) — the
number of test cases. Description of the test cases follows.

The first line of each test case contains a single integer n (1≤n≤500) — the length of the
permutation.

The second line of each test case contains n integers p1,p2,…,pn (1≤pi≤n) — the elements of the
permutation.

Output

For each test case print the lexicographically smallest permutation you can obtain.

Example
Input
Copy

4
1
1
3
2 1 3
4
1 4 2 3
5
1 2 3 4 5

Output
Copy

1
1 2 3
1 2 4 3
1 2 3 4 5

Note

In the first test case, the permutation has length 1, so the only possible segment is [1,1]. The
resulting permutation is [1].

In the second test case, we can obtain the identity permutation by reversing the segment [1,2]. The
resulting permutation is [1,2,3].

In the third test case, the best possible segment is [2,3]. The resulting permutation is [1,2,4,3].

In the fourth test case, there is no lexicographically smaller permutation, so we can leave it
unchanged by choosing the segment [1,1]. The resulting permutation is [1,2,3,4,5].
*/

const lines = []

require('readline').createInterface({
  input: process.stdin
}).on('line', line => lines.push(line))

process.stdin.on('end', () => {
  output(main(lines))
})

function output(res) {
  for (const r of res) {
    console.log(r.join(' '), '')
  }
}

function swap(arr, i, j) {
  [arr[i], arr[j]] = [arr[j], arr[i]]
}

function reverse(arr, i, j) {
  while (i < j) swap(arr, i++, j--)
}

function solve(n, nums) {
  for (let i = 0; i < n; i++) {
    if (nums[i] !== i + 1) {
      let j = i + 1
      while (j < n && nums[j] !== i + 1) j++
      reverse(nums, i, j)
      break
    }
  }
  return nums
}

function main(lines) {
  let l = 0
  let t = Number(lines[l++])
  const res = []
  for (; t; t--) {
    const n = Number(lines[l++])
    const nums = lines[l++].split(' ').map(Number)
    res.push(solve(n, nums))
  }
  return res
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

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

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

        let result = [...arr];

        let startRevIndex;
        let endRevIndex;
        let lowestNumToFind;

        for (let i=0; i<lengthOfArr; i++) {
            if (arr[i] === (i+1) && startRevIndex === undefined) {
                continue;
            }

            if (lowestNumToFind === undefined) {
                lowestNumToFind = i+1;
                startRevIndex = i;
                continue;
            }

            if (arr[i] === lowestNumToFind) {
                endRevIndex = i;

                for (let j=0; j<= endRevIndex - startRevIndex; j++) {
                    result[startRevIndex + j] = arr[endRevIndex-j];
                }

                break;
            }
        }

        console.log(result.join(" "));
    }

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

"use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// out/FinalCode/Input.js
var require_Input = __commonJS({
  "out/FinalCode/Input.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var Input = class {
      constructor(inputData) {
        this.inputWords = [];
        this.inputStream = "";
        this.inputWordsLength = 0;
        this.inputWordsCount = 0;
        this.set_stream = (chunk) => {
          this.inputStream += chunk;
        };
        this.settle_stream = () => {
          let re = /\s+/;
          this.inputWords = this.inputStream.split(re);
          this.inputWordsLength = this.inputWords.length;
        };
        this.getNextWord = () => {
          this.inputWordsCount++;
          if (this.inputWordsLength < this.inputWordsCount) {
            return "";
          }
          return this.inputWords[this.inputWordsCount - 1];
        };
        this.getLength = () => {
          return this.inputWordsLength;
        };
        this.getEveryWord = () => {
          return this.inputWords;
        };
        this.getNextString = () => {
          return this.getNextWord();
        };
        this.getNextBigInt = () => {
          return BigInt(this.getNextWord());
        };
        this.getNextNumber = () => {
          return Number(this.getNextWord());
        };
        this.getNextInt = () => {
          return parseInt(this.getNextWord(), 10);
        };
        this.getNextFloat = () => {
          return parseFloat(this.getNextWord());
        };
        this.inputStream = inputData;
      }
    };
    exports2.default = Input;
  }
});

// out/typescript_competitive_programming.js
var __importDefault = exports && exports.__importDefault || function(mod) {
  return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Input_1 = __importDefault(require_Input());
var rw = new Input_1.default("");
var write = (output_element) => {
  process.stdout.write(output_element);
};
var writeLine = (output_element) => {
  write(String(output_element) + "\n");
};
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", (chunk) => {
  rw.set_stream(chunk);
});
process.stdin.on("end", () => {
  rw.settle_stream();
  main_func();
});
var main_func = () => {
  let test = rw.getNextInt();
  for (let index = 0; index < test; index++) {
    let n = rw.getNextInt();
    let arr = new Array(n);
    let id = -1;
    let min = 1e4;
    let start = -1;
    for (let idx = 0; idx < n; idx++) {
      arr[idx] = rw.getNextInt();
      if (arr[idx] !== idx + 1) {
        if (start === -1) {
          start = idx;
        }
        if (arr[idx] < min) {
          id = idx;
          min = arr[idx];
        }
      }
    }
    if (start !== -1) {
      for (let idx = 0; idx < (id - start) / 2; idx++) {
        [arr[start + idx], arr[id - idx]] = [arr[id - idx], arr[start + idx]];
      }
    }
    for (let idx = 0; idx < n; idx++) {
      write(`${arr[idx]} `);
    }
    writeLine(" ");
  }
};

"use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};

// out/FinalCode/Input.js
var require_Input = __commonJS({
  "out/FinalCode/Input.js"(exports2) {
    "use strict";
    Object.defineProperty(exports2, "__esModule", { value: true });
    var Input = function() {
      function Input2(inputData) {
        var _this = this;
        this.inputWords = [];
        this.inputStream = "";
        this.inputWordsLength = 0;
        this.inputWordsCount = 0;
        this.set_stream = function(chunk) {
          _this.inputStream += chunk;
        };
        this.settle_stream = function() {
          var re = /\s+/;
          _this.inputWords = _this.inputStream.split(re);
          _this.inputWordsLength = _this.inputWords.length;
        };
        this.getNextWord = function() {
          _this.inputWordsCount++;
          if (_this.inputWordsLength < _this.inputWordsCount) {
            return "";
          }
          return _this.inputWords[_this.inputWordsCount - 1];
        };
        this.getLength = function() {
          return _this.inputWordsLength;
        };
        this.getEveryWord = function() {
          return _this.inputWords;
        };
        this.getNextString = function() {
          return _this.getNextWord();
        };
        this.getNextBigInt = function() {
          return BigInt(_this.getNextWord());
        };
        this.getNextNumber = function() {
          return Number(_this.getNextWord());
        };
        this.getNextInt = function() {
          return parseInt(_this.getNextWord(), 10);
        };
        this.getNextFloat = function() {
          return parseFloat(_this.getNextWord());
        };
        this.inputStream = inputData;
      }
      return Input2;
    }();
    exports2.default = Input;
  }
});

// out/typescript_competitive_programming.js
var __importDefault = exports && exports.__importDefault || function(mod) {
  return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var Input_1 = __importDefault(require_Input());
var rw = new Input_1.default("");
var write = function(output_element) {
  process.stdout.write(output_element);
};
var writeLine = function(output_element) {
  write(String(output_element) + "\n");
};
process.stdin.resume();
process.stdin.setEncoding("utf-8");
process.stdin.on("data", function(chunk) {
  rw.set_stream(chunk);
});
process.stdin.on("end", function() {
  rw.settle_stream();
  main_func();
});
var main_func = function() {
  var _a;
  var test = rw.getNextInt();
  for (var index = 0; index < test; index++) {
    var n = rw.getNextInt();
    var arr = new Array(n);
    var id = -1;
    var min = 1e4;
    var start = -1;
    for (var idx = 0; idx < n; idx++) {
      arr[idx] = rw.getNextInt();
      if (arr[idx] !== idx + 1) {
        if (start === -1) {
          start = idx;
        }
        if (arr[idx] < min) {
          id = idx;
          min = arr[idx];
        }
      }
    }
    if (start !== -1) {
      for (var idx = 0; idx < (id - start) / 2; idx++) {
        _a = [arr[id - idx], arr[start + idx]], arr[start + idx] = _a[0], arr[id - idx] = _a[1];
      }
    }
    for (var idx = 0; idx < n; idx++) {
      write(arr[idx] + " ");
    }
    writeLine(" ");
  }
};

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

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

const calc = (n, P)=>{
  let i;
  for (i=0; P[i]==i+1 && i<n; i++);
  if (i==n){
    return P;
  }
  let l = i;
  let minI = i;
  for (let j=i; j<n; j++){
    if (P[j]<P[minI])
      minI = j;
  }
  let r = minI;
  for (i=l; i<(l+r)/2; i++){
    let j = r-(i-l);
    let tmp = P[i];
    P[i] = P[j]
    P[j] = tmp
  }
  L({l, r, P})
  return P
};

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

E.calc = calc;

"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++];
}

const reverse = (perm, l, r) => {
	return [
		...perm.slice(0, l),
		...perm.slice(l, r + 1).reverse(),
		...perm.slice(r + 1),
	];
};

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

	for (let i = 0; i < testCount; i++) {
		let permLength = +readline();
		let perm = readline().split(" ");

		let startIndex = 0;

		const sorted = perm.slice().sort((a, b) => a - b);

		while (
			sorted[startIndex] === perm[startIndex] &&
			startIndex < perm.length
		) {
			startIndex++;
		}

		if (startIndex === perm.length) {
			console.log(perm.join(" "));
		} else {
			const swapIndex = perm.indexOf(sorted[startIndex]);

			console.log(reverse(perm, startIndex, swapIndex).join(" "));
		}
	}
}

let text = '';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', str => {
    if (str === '\r\n' || str === '\n') {
        process.stdin.emit('end');
    } else {
        text += str;
    }
});

process.stdin.on('end', () => {
    const input = text.trim().replace(/\r/g, '').split('\n');
    const total = +input[0];
    for (let i = 1; i <= total; i++) {
        console.log(solve(input[i * 2]));
    }

    process.exit();
});

function solve(str) {
    const numbers = str.split(' ').map(ele => + ele);
    for (let i = 0; i < numbers.length; i++) {
        if (numbers[i] !== i + 1) {
            for (var j = i + 1; j < numbers.length; j++) {
                if (numbers[j] === i + 1) {
                    break;
                }
            }
            while(i < j) {
                [numbers[i], numbers[j]] = [numbers[j], numbers[i]];
                i++;
                j--;
            }
            break;
        }
    }
    return numbers.join(' ');
}

'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 left = 0;
        let right = 0;
        while (arr[left] === left + 1) left++;
        if (left === arr.length - 1) output(arr.join(' '));
        right = left + 1;
        while (!isNaN(arr[right]) && arr[right] !== left + 1) right++;
        let rev = arr.slice(left, right + 1).reverse();
        let res = [...arr.slice(0, left), ...rev, ...arr.slice(right + 1)];
        output(res.join(' '));
    }
}

'use strict';

function solve(n, a) {
  let l = -1,
      r = -1,
      min = -1;
  for (let i = n - 1; i >= 0; i--) {
    if (a[i] > a[min]) {
      l = i;
      r = min;
    }
    if (min === -1 || a[min] > a[i]) min = i;
  }
  for (let i = l, j = r; i < j; i++, j--) {
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a.join(' ');
}

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

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

'use strict';

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

let inputString = '';
let currentLine = 0;

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

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

  main();
});

function readline() {
  return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

function main() {
  const tests_count = parseInt(readline());
  for (var test = 0; test < tests_count; test++) {
    const n = parseInt(readline());
    const permutation = readline().split(" ").filter(s => s.trim().length !== 0).map(s => parseInt(s.trim()));
    console.log(bestPermutation(permutation).join(" "));
  }
}

function bestPermutation(p) {
  let pivot_min_idx = findNextMin(p, 1);
  if (pivot_min_idx >= p.length)
    // Array is sorted
    return p;
  else {
    // Find biggest number after pivot
    let right_min_idx = findNextBestMin(p, pivot_min_idx);
    // Find smaller number before pivot
    let left_min_idx = pivot_min_idx - 1;
    while (left_min_idx >= 0 && p[left_min_idx] > p[right_min_idx])
      left_min_idx--;
    return permutate(p, left_min_idx + 1, right_min_idx)
  }
}
function findNextMin(p, ix) {
  while (ix < p.length && p[ix] > p[ix - 1]) ix++;
  return ix;
}
function findNextBestMin(p, ix) {
  let best = ix++;
  for (; ix < p.length; ix++)
    if (p[ix] < p[best]) best = ix;
  return best;
}
function permutate(p, ini, end) {
  const iTop = Math.floor((1 + end - ini) / 2);
  for (let i = 0; i < iTop; i++) swap(p, ini + i, end - i);
  return p;
}
function swap(p, i, j) {
  if (i !== j) {
    let aux = p[i];
    p[i] = p[j];
    p[j] = aux;
  }
}

const readline = require('readline');

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

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

const main = async () => {
    const use_cases = await it.next();
    let t = use_cases.value;
    while(t--)
    {
        const n = Number((await it.next()).value);
        let arr = (await it.next()).value.split(' ').map( x => Number(x));
        let left_index = -1;
        let required_elm = -1;
        let right_index = -1;
        let flag = false;
        for(let i=0; i< n; i++)
        {
            if( arr[i] > i+1 && !flag)
            {
                left_index = i;
                required_elm = i+1;
                flag = true;
            }
            if( arr[i] === required_elm)
            {
                right_index = i;
                break;
            }
        }
        if(right_index !== -1)
        {
            let j = right_index;
            for(let i=left_index; i<= left_index + (((right_index - left_index)/2) | 0); i++)
            {
                let temp = arr[i]
                arr[i] = arr[j];
                arr[j] = temp;
                j--;
            }
        }
        console.log(arr.join(' '));
    }

}
main();

const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trim().split('\n');
let currentline = 0;
function readline(){
    return input[currentline++];
}

var T = readline();
for(var q=1;q<=T;q++) {
            var n = readline();
            var a = readline().split(" ").map(w => parseInt(w))
            var s = []
            for(var i=0;i<n;i++) s[i]=a[i]
            s.sort(function(ar,br){ return ar-br })
            var i=0;
            var j=0;
            while(s[i]==a[j] && (j<n && i<n)) {
            	i++;
            	j++;
            }
            for(var p=j;p<n;p++) {
            	if(a[p]==s[i]) break;
            }

            while(j<=p) {
            	var cache = a[j]
            	a[j] = a[p]
            	a[p] = cache;
            	j++;
            	p--;
            }
            console.log(a.join(' '));
}

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ');
    reverse(datas, n);
}

function reverse(data, n) {
	var l = -1, r = 0;
	var i;
	for (i = 0; i < n; i++) {
	    data[i] = parseInt(data[i]);
	    if (data[i] == l+1) {
	        r = i;
	        break;
	    }
	    if (data[i] != i+1 && l == -1) {
	        l = i;
	    }
	}
	var res = '';
	l = -1 ? 0 : l;
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var t = parseInt(readline());
while (t--) {
    var n = parseInt(readline());
    var datas = readline().split(' ').map((x) => parseInt(x));
    reverse(datas, n);
}

function reverse(data, n) {
	var l = 0, r = 0, max = 0, min = 0;
	var i;

	for (i = 1; i < n; i++) {
	    if ((min === 0 && data[i] < data[max]) || data[i] < data[min]){
			min = i;
			r = i;
		}
		if (max === 0 && data[i] > data[i - 1] + 1 && min === 0) {
			max = i;
			l = i;
		}
	}
	var res = '';
	for (i = 0; i < l; i++) {
		res = res + data[i] + ' ';
	}
	for (i = r; i>=l; i--) {
		res = res + data[i] + ' ';
	}
	for (i = r+1; i < n; i++) {
		res = res + data[i] + ' ';
	}
	print(res);
}

var limit = parseInt(readline());
for (var i = 0; i < limit; i++)
{
    var caseLength = parseInt(readline());
    var caseArray = readline().split(" ");
    var caseMap = new Map();
    for (var j = 0; j < caseLength; j++)
    {
        caseMap[caseArray[j]] = j;
    }
    var start = 0;
    var flag = false;
    var result = "";
    for (var j = 0; j < caseLength; j++)
    {
        if (caseArray[j] !== `${j+1}`)
        {
            var startRevIndex = caseMap[`${j+1}`];
            if (startRevIndex !== null)
            {
                for (var k = startRevIndex; k >= j; k--)
                {
                    result += `${caseArray[k]} `;
                }
                start = startRevIndex;
                flag = true;
                break;
            }
        }
        else result += `${caseArray[j]} `;
    }
    if (flag)
    {
        for (var j = start; j < caseLength; j++)
        {
            result += `${caseArray[j]} `;
        }
    }
    print(result);
}

"use strict";

//let startTime = Date.now();

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

let inputString = "";
let currentLine = 0;

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

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

    main();
});

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

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

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

        let result = arr;

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

            if (b < a) {
                result[i+1] = a;
                result[i] = b;
                break;
            }
        }

        console.log(result.toString().replace(/,/g, " "));
    }

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

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

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

const calc = (n, P)=>{
  let i;
  for (i=0; P[i]==i+1 && i<n; i++);
  if (i==n){
    return P;
  }
  let l = i;
  let minI = i;
  for (let j=i; j<n; j++){
    if (P[j]<P[minI])
      minI = j;
  }
  let r = minI;
  for (i=l; i<(l+r)/2; i++){
    let j = r-(l-i);
    let tmp = P[i];
    P[i] = P[j]
    P[j] = tmp
  }
  return P
};

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

E.calc = calc;

"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++];
}

const reverse = (perm, l, r) => {
	return [
		...perm.slice(0, l),
		...perm.slice(l, r + 1).reverse(),
		...perm.slice(r + 1),
	];
};

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

	for (let i = 0; i < testCount; i++) {
		let permLength = +readline();
		let perm = readline().split(" ");

		let startIndex = 0;

		const sorted = perm.slice().sort();

		while (
			sorted[startIndex] === perm[startIndex] &&
			startIndex < perm.length
		) {
			startIndex++;
		}

		if (startIndex === perm.length) {
			console.log(perm.join(" "));
		} else {
			const swapIndex = perm.indexOf(sorted[startIndex]);

			console.log(reverse(perm, startIndex, swapIndex).join(" "));
		}
	}
}


There are $$$n$$$ people in this world, conveniently numbered $$$1$$$ through $$$n$$$. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let $$$d(a,b)$$$ denote the debt of $$$a$$$ towards $$$b$$$, or $$$0$$$ if there is no such debt.Sometimes, this becomes very complex, as the person lending money can run into financial troubles before his debtor is able to repay his debt, and finds himself in the need of borrowing money. When this process runs for a long enough time, it might happen that there are so many debts that they can be consolidated. There are two ways this can be done:  Let $$$d(a,b) > 0$$$ and $$$d(c,d) > 0$$$ such that $$$a \neq c$$$ or $$$b \neq d$$$. We can decrease the $$$d(a,b)$$$ and $$$d(c,d)$$$ by $$$z$$$ and increase $$$d(c,b)$$$ and $$$d(a,d)$$$ by $$$z$$$, where $$$0 < z \leq \min(d(a,b),d(c,d))$$$.  Let $$$d(a,a) > 0$$$. We can set $$$d(a,a)$$$ to $$$0$$$. The total debt is defined as the sum of all debts:$$$$$$\Sigma_d = \sum_{a,b} d(a,b)$$$$$$Your goal is to use the above rules in any order any number of times, to make the total debt as small as possible. Note that you don't have to minimise the number of non-zero debts, only the total debt.

The first line contains two space separated integers $$$n$$$ ($$$1 \leq n \leq 10^5$$$) and $$$m$$$ ($$$0 \leq m \leq 3\cdot 10^5$$$), representing the number of people and the number of debts, respectively. $$$m$$$ lines follow, each of which contains three space separated integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n, u_i \neq v_i$$$), $$$d_i$$$ ($$$1 \leq d_i \leq 10^9$$$), meaning that the person $$$u_i$$$ borrowed $$$d_i$$$ burles from person $$$v_i$$$.

On the first line print an integer $$$m'$$$ ($$$0 \leq m' \leq 3\cdot 10^5$$$), representing the number of debts after the consolidation. It can be shown that an answer always exists with this additional constraint. After that print $$$m'$$$ lines, $$$i$$$-th of which contains three space separated integers $$$u_i, v_i, d_i$$$, meaning that the person $$$u_i$$$ owes the person $$$v_i$$$ exactly $$$d_i$$$ burles. The output must satisfy $$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$ and $$$0 < d_i \leq 10^{18}$$$. For each pair $$$i \neq j$$$, it should hold that $$$u_i \neq u_j$$$ or $$$v_i \neq v_j$$$. In other words, each pair of people can be included at most once in the output.

NoteIn the first example the optimal sequence of operations can be the following:  Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 2$$$, $$$d = 3$$$ and $$$z = 5$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(2, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(1, 2) = 5$$$, $$$d(1, 3) = 5$$$, all other debts are $$$0$$$. In the second example the optimal sequence of operations can be the following:  Perform an operation of the first type with $$$a = 1$$$, $$$b = 2$$$, $$$c = 3$$$, $$$d = 1$$$ and $$$z = 10$$$. The resulting debts are: $$$d(3, 2) = 10$$$, $$$d(2, 3) = 15$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the first type with $$$a = 2$$$, $$$b = 3$$$, $$$c = 3$$$, $$$d = 2$$$ and $$$z = 10$$$. The resulting debts are: $$$d(2, 2) = 10$$$, $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 2$$$. The resulting debts are: $$$d(3, 3) = 10$$$, $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 3$$$. The resulting debts are: $$$d(2, 3) = 5$$$, $$$d(1, 1) = 10$$$, all other debts are $$$0$$$;  Perform an operation of the second type with $$$a = 1$$$. The resulting debts are: $$$d(2, 3) = 5$$$, all other debts are $$$0$$$.

function wr(...x) {
  console.log(...x)
}

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))

  const [n, m] = arr.shift().split(' ').map(a => parseInt(a))

  const ms = new Array(m)
  // const debts = new Array(n).fill(0)
  const debts = new Array(n)
  for(let i = 0; i < n; i++) {
    debts[i] = [0, i + 1]
  }
  const ans = []

  for(let j = 0; j < m; j++) {
    ms[j] = arr[j].split(' ').map(a => parseInt(a))
    const [u, v, d] = ms[j]
    debts[u - 1][0] -= d
    debts[v - 1][0] += d
  }

  // debts.sort((a, b) => a[0] - b[0])

  let x = 0

  for(let i = 0; i < n; i++) {
    while(debts[i][0] < 0){
      while(debts[x][0] <= 0) x++
      let t = Math.min(-debts[i][0], debts[x][0])
      debts[i][0] += t
      debts[x][0] -= t
      ans.push([debts[i][1], debts[x][1], t])
    }
  }

  wr(ans.length)

  for(let i = 0, len = ans.length; i < len; i++) {
    wr(ans[i].join(' '))
  }

})

function wr(x) {
  console.log(x)
}

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

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

process.stdin.on('end', () => {
  arr = arr.split('\n').map(a => a.replace(/(\r\n|\n|\r)/gm, ''))

  const [n, m] = arr.shift().split(' ').map(a => parseInt(a))

  const ms = new Array(m)
  // const debts = new Array(n).fill(0)
  const debts = new Array(n)
  for(let i = 0; i < n; i++) {
    debts[i] = [0, i + 1]
  }
  const ans = []

  for(let j = 0; j < m; j++) {
    ms[j] = arr[j].split(' ').map(a => parseInt(a))
    const [u, v, d] = ms[j]
    debts[u - 1][0] -= d
    debts[v - 1][0] += d
  }

  debts.sort((a, b) => a[0] - b[0])

  // console.log(debts)
  let l = 0
  let r = n - 1

  while(l < r) {
    // console.log(l,r)
    let lf = debts[l][0]
    let rf = debts[r][0]

    if(rf < (-lf)) {
      debts[l][0] += rf
      debts[r][0] -= rf
      ans.push([debts[l][1], debts[r][1], rf])
      r --
    }
    else if(rf > (-lf)) {
      debts[l][0] -= lf
      debts[r][0] += lf
      ans.push([debts[l][1], debts[r][1], (-lf)])
      l++
    }
    else {
      debts[l][0] -= lf
      debts[r][0] += lf
      ans.push([debts[l][1], debts[r][1], rf])
      l++
      r--
    }
  }
  wr(ans.length)

  for(let i = 0, len = ans.length; i < len; i++) {
    wr(ans[i].join(' '))
  }

})


A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.You are given a binary string $$$s$$$ of length $$$n$$$. Construct two balanced bracket sequences $$$a$$$ and $$$b$$$ of length $$$n$$$ such that for all $$$1\le i\le n$$$:   if $$$s_i=1$$$, then $$$a_i=b_i$$$  if $$$s_i=0$$$, then $$$a_i\ne b_i$$$ If it is impossible, you should report about it.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ is even). The next line contains a string $$$s$$$ of length $$$n$$$, consisting of characters 0 and 1. The sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$.

If such two balanced bracked sequences exist, output "YES" on the first line, otherwise output "NO". You can print each letter in any case (upper or lower). If the answer is "YES", output the balanced bracket sequences $$$a$$$ and $$$b$$$ satisfying the conditions on the next two lines. If there are multiple solutions, you may print any.

NoteIn the first test case, $$$a=$$$"()()()" and $$$b=$$$"((()))". The characters are equal in positions $$$1$$$, $$$3$$$, $$$4$$$, and $$$6$$$, which are the exact same positions where $$$s_i=1$$$.In the second test case, $$$a=$$$"()()((()))" and $$$b=$$$"(())()()()". The characters are equal in positions $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, which are the exact same positions where $$$s_i=1$$$.In the third test case, there is no solution.

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
	input: process.stdin, output: process.stdout
});
var obj; var inLine = []; var outputList = [];var retcode = new Set();
read.on('line', function(input){
	var tmp = input.split(' ');
	for(var i = 0; i < tmp.length; i++){
		inLine.push(tmp[i]);
		if(i == tmp.length - 1){
			retcode.add(inLine.length);
		}
	}
});
read.on('close', function(){
	obj = init(inLine);
	console.error('\n↑入力 ↓出力');
	Main();
	console.log(myconv(outputList, 9));
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextArray(size, code){
	var ret = new Array(size);
	for(var i = 0; i < size; i++){
		if(code == 'int'){
			ret[i] = nextInt();
		}else{
			ret[i] = next();
		}
	}
	return ret;
}
function nextIntArray(size){return nextArray(size, 'int');} function nextStrArray(size){return nextArray(size, 'str');}
function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();} function nextInt(){return myconv(next(),1);}
function getCountMap(list){
	var map = {};
	for(var i = 0; i < list.length; i++){
		if(map[list[i]] == null){
			map[list[i]] = 0;
		}
		map[list[i]]++;
	}
	return map;
}
function init(input){
	return {
		list : input, index : 0, max : input.length,
		hasNext : function(){return (this.index < this.max);},
		next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}},
		isReturn : function(){return retcode.has(this.index);}
	};
}
function myout(s){outputList.push(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
function isReturn(){return obj.isReturn();}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------

function Main(){
	var t = nextInt();
	for(var i = 0; i < t; i++){
		var N = nextInt();
		var b = next();
		if(b[0] == "0" || b[N - 1] == "0"){
			myout("NO");
			continue;
		}
		var one = 0;
		var zero = 0;
		for(var j = 0; j < N; j++){
			if(b[j] == "1"){
				one++;
			}else{
				zero++;
			}
		}
		if(one % 2 == 0 && zero % 2 == 0){
			myout("YES");
			var L = new Array(N);
			var R = new Array(N);
			var Ocount = 0;//max:N / 2
			var Zcount = 0;//max: N /2
			for(var j = 0; j < N; j++){
				if(b[j] == "1"){
					if(Ocount < one / 2){
						Ocount++;
						L[j] = "(";
						R[j] = "(";
					}else{
						L[j] = ")";
						R[j] = ")";
					}
				}else{
					if(Zcount % 2 == 0){
						L[j] = "(";
						R[j] = ")";
					}else{
						L[j] = ")";
						R[j] = "(";
					}
					Zcount++;
				}
			}
			myout(myconv(L, 0));
			myout(myconv(R, 0));
		}else{
			myout("NO");
		}
	}
	/*var N = nextInt();
	var ok = new Set();
	for(var i = 0; i < (1 << N); i++){
		var s = "";
		for(var j = 0; j < N; j++){
			s += ((i & (1 << j)) != 0) ? "1" : "0";
		}
		for(var j = 0; j < (1 << N); j++){
			var L = "";
			var R = "";
			for(var k = 0; k < N; k++){
				if((j & (1 << k)) != 0){
					if(s[k] == "0"){
						L += "(";
						R += ")";
					}else{
						L += "(";
						R += "(";
					}
				}else{
					if(s[k] == "0"){
						L += ")";
						R += "(";
					}else{
						L += ")";
						R += ")";
					}
				}
			}
			var Li = [];
			var Ri = [];
			for(var k = 0; k < N; k++){
				if(L[k] == "("){
					Li.push("(");
				}else if(Li[Li.length - 1] == "("){
					Li.pop();
				}else{
					Li.push(")");
				}
				if(R[k] == "("){
					Ri.push("(");
				}else if(Ri[Ri.length - 1] == "("){
					Ri.pop();
				}else{
					Ri.push(")");
				}
			}
			if(Li.length == 0 && Ri.length == 0){
				myerr({s, L, R});
				ok.add(s);
			}
		}
	}
	myerr(ok);*/
}

'use strict';

function solve(n, s) {
  const len0 = s.split('').filter(char => char === '0').length;
  if (s[0] === '0' || s[s.length - 1] === '0' || len0 & 1) return 'NO';
  let res1 = [],
      res2 = [],
      pre = 0;
  for (let i = 0; i < n; i++) {
    if (s[i] === '0') {
      if (pre === 0) {
        res1[i] = '(';
        res2[i] = ')';
      } else {
        res1[i] = ')';
        res2[i] = '(';
      }
      pre ^= 1;
    }
  }
  {
    let l = n / 2 - len0 / 2;
    for (let i = 0; i < n; i++) {
      if (s[i] === '0') continue;
      if (l) {
        res1[i] = '(';
        res2[i] = '(';
        l--;
      } else {
        res1[i] = ')';
        res2[i] = ')';
      }
    }
  }
  return `YES\n${res1.join('')}\n${res2.join('')}`;
}

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

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

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

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

var deb; const log = msg => (typeof deb != "undefined") && console.log("DEBUG", msg);

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const s = rl();

		let cnt = [0, 0];
		for (let i = 0; i < n; i++) {
			cnt[s[i]]++;
		}

		if (s[0] == 0 || s[n-1] == 0 || cnt[0] & 1) {
			console.log('NO');
			continue;
		}

		const ans = [[], []];
		for (let i = 0, use, cntOpen = 0, last; i < n; i++) {
			if (s[i] == 1) {
				use = cntOpen < cnt[1]/2 ? '((' : '))';
				cntOpen++;
			} else {
				use = last ? "()" : ")(";
				last ^= 1;
			}
			ans[0][i] = use[0];
			ans[1][i] = use[1];
		}

		console.log('YES');
		console.log(ans[0].join(''));
		console.log(ans[1].join(''));
	}
}


One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.

The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.

In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.

print(function(n) {

	var l = 0,
		r = 0;
	for (var i = 0; i < n; i++)
		readline().split(' ').map(Number).reduce(function(ll, rr) {
			l += ll;
			r += rr;
		});

	return Math.min(n - l, l) + Math.min(n - r, r);

}(+readline()));

"use strict";

//readline().split(' ').map(Number);

function sec(){
    print("F")
}

function main(){
    var t = readline();
    var a = 0,b = 0;
    for (var i = 0;i<t;i++){
        var arr = readline().split(' ').map(Number);
        a += arr[0];
        b += arr[1];
    }
    print(Math.min(a,t-a)+Math.min(b,t-b));
}

main();

let inputString = "";
let currentLine = 0;
process.stdin.on("data", (data) => {
  inputString += data;
});
process.stdin.on("end", function () {
  inputString = inputString
    .trim()
    .split("\n")
    .map((str) => str.trim());
  main();
});
function readLine() {
  return inputString[currentLine++];
}
function main() {
  let t = +readLine();
  let [l0, l1] = [0, 0];
  let [r0, r1] = [0, 0];
  while (t--) {
    const [left, right] = readLine()
      .split(" ")
      .map((n) => parseInt(n));

    if (left === 0) l0++;
    else l1++;

    if (right === 0) r0++;
    else r1++;
  }
  console.log(`${Math.min(l0, l1) + Math.min(r0, r1)}`);
}

//Cupboards

const {EOL} = require('os');

let inp = '';

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

process.stdin.on('end', () => {
    let lines = inp.split(EOL);

	let cnt = [0, 0, 0, 0]; //c, l, o, r
	for(let i in lines)  {
		if(lines[i] == '0 0')  {
			cnt[0]++;
		}
		if(lines[i] == '1 0')  {
			cnt[1]++;
		}
		if(lines[i] == '1 1')  {
			cnt[2]++;
		}
		if(lines[i] == '0 1')  {
			cnt[3]++;
		}
	}

	let t = [];
	for(let i = 0; i < 4; i++)  {
		t.push(cnt[(i + 1) % 4] + cnt[(i + 3) % 4] + (2 * cnt[(i + 2) % 4]));
	}

	process.stdout.write(Math.min(...t) + '');

    return;
});

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

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

  const [x, y] = d.split(' ').map(Number);

  if (x === 0) {
    c1++;
  }
  else {
    o1++;
  }

  if (y === 0) {
    c2++;
  }
  else {
    o2++;
  }

  c++;
});

rl.on('close', () => {
  let ans = n - Math.max(o1, c1) + n - Math.max(o2, c2);

  console.log(ans);
});

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

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

  const [x, y] = d.split(' ').map(Number);

  l += x;
  r += y;

  c++;
});

rl.on('close', () => {
  const ans = Math.min(n - l, l) + Math.min(n - r, r);

  console.log(ans);
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let m = n;
	let cl = {},
		cr = {};
	while (n--) {
		let [l, r] = readLine()
			.split(' ')
			.map(x => x >> 0);

		cl[l] = (cl[l] || 0) + 1;
		cr[r] = (cr[r] || 0) + 1;
	}

	let res = 0;
	let lt = Math.min(...Object.values(cl));
	lt = lt === m ? 0 : lt;
	let rt = Math.min(...Object.values(cr));
	rt = rt === m ? 0 : rt;

	res = lt + rt;
	console.log(res);
}

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

function main() {
    let cupBoards = parseInt(readLine());
    let leftDoors = [];
    let rightDoors = [];
    for (let i = 0; i < cupBoards; i++) {
        const doorsArray = readLine().split(' ').map(Number);
        let [left, right] = doorsArray;
        leftDoors.push(left);
        rightDoors.push(right);
    }

    function NumberInArray(array, number) {
        let count = 0;
        for (let i = 0; i < array.length; i++) {
            if (array[i] === number) {
                count++;
            }
        }
        return count;
    }
    let ZerosinLeftArray = NumberInArray(leftDoors, 0);
    let OnesinLeftArray = NumberInArray(leftDoors, 1);
    let ZerosinRightArray = NumberInArray(rightDoors, 0);
    let OnesinRightArray = NumberInArray(rightDoors, 1);
    if (ZerosinLeftArray === cupBoards && ZerosinRightArray === cupBoards) {
        console.log(0);
        return;
    }
    if (OnesinRightArray === cupBoards && OnesinLeftArray == cupBoards) {
        console.log(0);
        return;
    }
    let changesinLeftDoors;
    if (
        ZerosinLeftArray > OnesinLeftArray
        // ZerosinLeftArray > ZerosinRightArray
    ) {
        changesinLeftDoors = OnesinLeftArray;
        // let changesinRightDoors = ZerosinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    } else if (ZerosinLeftArray < OnesinLeftArray) {
        changesinLeftDoors = ZerosinLeftArray;
        // let changesinRightDoors = OnesinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    } else if (ZerosinLeftArray === OnesinLeftArray) {
        changesinLeftDoors = ZerosinLeftArray;
    }

    let changesinRightDoors;
    if (ZerosinRightArray > OnesinRightArray) {
        changesinRightDoors = OnesinRightArray;
    } else if (ZerosinRightArray < OnesinRightArray) {
        changesinRightDoors = ZerosinRightArray;
    } else if (ZerosinRightArray === OnesinRightArray) {
        changesinRightDoors = ZerosinRightArray;
    }

    console.log(changesinLeftDoors + changesinRightDoors);
}

let data = '';
process.stdin.on('data', c => data += c);
const solution = () => {
	let line = data.split('\n');
	let n = parseInt(line[0], 10);
	let r = 0;
	let l = 0;
	for(let i = 1; i <= n; i++){
		let [x, y] = line[i].split(' ').map(v => parseInt(v,10));
		l += x;
		r += y;
	}
	console.log(Math.min(l, n - l) + Math.min(r, n - r));

};

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

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

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

  const [x, y] = d.split(' ').map(Number);

  if (x === 0) {
    c1++;
  }
  else {
    o1++;
  }

  if (y === 0) {
    c2++;
  }
  else {
    o2++;
  }

  c++;
});

rl.on('close', () => {
  let ans = Math.min(o1 + c2, c1 + o2);

  if (o1 === o2 && c1 === c2) {
    ans = 0;
  }

  console.log(ans);
});

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

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

  const [x, y] = d.split(' ').map(Number);

  if (x === 0) {
    c1++;
  }
  else {
    o1++;
  }

  if (y === 0) {
    c2++;
  }
  else {
    o2++;
  }

  c++;
});

rl.on('close', () => {
  const ans = Math.min(o1 + c2, c1 + o2);
  console.log(ans);
});

let inputString = '';
let currentLine = 0;
process.stdin.on('data', data => {
	inputString += data;
});
process.stdin.on('end', function () {
	inputString = inputString
		.trim()
		.split('\n')
		.map(str => str.trim());
	main();
});

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

function isPrime(x) {
	let s = Math.sqrt(x);
	let i = 2;
	while (i <= s) {
		if (x % i === 0) {
			return false;
		}
		i++;
	}
	return true;
}

function main() {
	let n = readLine() >> 0;
	let cl = {},
		cr = {};
	while (n--) {
		let [l, r] = readLine()
			.split(' ')
			.map(x => x >> 0);

		cl[l] = (cl[l] || 0) + 1;
		cr[r] = (cr[r] || 0) + 1;
	}

	let res = 0;
	res = Math.min(...Object.values(cl)) + Math.min(...Object.values(cr));
	console.log(res);
}

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

function main() {
    let cupBoards = parseInt(readLine());
    let leftDoors = [];
    let rightDoors = [];
    for (let i = 0; i < cupBoards; i++) {
        const doorsArray = readLine().split(' ').map(Number);
        let [left, right] = doorsArray;
        leftDoors.push(left);
        rightDoors.push(right);
    }

    function NumberInArray(array, number) {
        let count = 0;
        for (let i = 0; i < array.length; i++) {
            if (array[i] === number) {
                count++;
            }
        }
        return count;
    }
    let ZerosinLeftArray = NumberInArray(leftDoors, 0);
    let OnesinLeftArray = NumberInArray(leftDoors, 1);
    let ZerosinRightArray = NumberInArray(rightDoors, 0);
    let OnesinRightArray = NumberInArray(rightDoors, 1);

    if (
        ZerosinLeftArray > OnesinLeftArray &&
        ZerosinLeftArray > ZerosinRightArray
    ) {
        let changesinLeftDoors = OnesinLeftArray;
        let changesinRightDoors = ZerosinRightArray;
        console.log(changesinLeftDoors + changesinRightDoors);
    } else {
        let changesinLeftDoors = ZerosinLeftArray;
        let changesinRightDoors = OnesinRightArray;
        console.log(changesinLeftDoors + changesinRightDoors);
    }
}

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

function main() {
    let cupBoards = parseInt(readLine());
    let leftDoors = [];
    let rightDoors = [];
    for (let i = 0; i < cupBoards; i++) {
        const doorsArray = readLine().split(' ').map(Number);
        let [left, right] = doorsArray;
        leftDoors.push(left);
        rightDoors.push(right);
    }

    function NumberInArray(array, number) {
        let count = 0;
        for (let i = 0; i < array.length; i++) {
            if (array[i] === number) {
                count++;
            }
        }
        return count;
    }
    let ZerosinLeftArray = NumberInArray(leftDoors, 0);
    let OnesinLeftArray = NumberInArray(leftDoors, 1);
    let ZerosinRightArray = NumberInArray(rightDoors, 0);
    let OnesinRightArray = NumberInArray(rightDoors, 1);
    if (ZerosinLeftArray === cupBoards && ZerosinRightArray === cupBoards) {
        console.log(0);
        return;
    }
    if (OnesinRightArray === cupBoards && OnesinLeftArray == cupBoards) {
        console.log(0);
        return;
    }
    let changesinLeftDoors;
    if (
        ZerosinLeftArray > OnesinLeftArray
        // ZerosinLeftArray > ZerosinRightArray
    ) {
        changesinLeftDoors = OnesinLeftArray;
        // let changesinRightDoors = ZerosinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    } else if (ZerosinLeftArray < OnesinLeftArray) {
        changesinLeftDoors = ZerosinLeftArray;
        // let changesinRightDoors = OnesinRightArray;
        // console.log(changesinLeftDoors + changesinRightDoors);
    }

    let changesinRightDoors;
    if (ZerosinRightArray > OnesinRightArray) {
        changesinRightDoors = OnesinRightArray;
    } else if (ZerosinRightArray < OnesinRightArray) {
        changesinRightDoors = ZerosinRightArray;
    }

    console.log(changesinLeftDoors + changesinRightDoors);
}