Problem:
Permutation

For given a sequence $A = \{a_0, a_1, ..., a_{n-1}\}$, print the previous permutation and the next permutation in lexicographic order.

Input

A sequence is given in the following format.

$n$
$a_0 \; a_1 \; ... \; a_{n-1}$

Output

Print the previous permutation, the given sequence and the next permutation in the 1st, 2nd and 3rd lines respectively.
Separate adjacency elements by a space character. Note that if there is no permutation, print nothing in the corresponding line.

Constraints

$1 \leq n \leq 9$

$a_i$ consist of $1, 2, ..., n$

Sample Input 1

3
2 1 3

Sample Output 1

1 3 2
2 1 3
2 3 1

Sample Input 2

3
3 2 1

Sample Output 2

3 1 2
3 2 1

Solution in JAVA (judge verdict: Accepted)

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main { 
	static Scanner scan = new Scanner(System.in);

    public static void main(String[] args) { 

    	int n = scan.nextInt();
    	String str = "";
    	
    	for(int i=0; i<n; i++) {
    		str += scan.nextInt();	//WARNING
    		if (i != n-1) str += " ";
    	}
    	
    	String str2 = "";
    	List<String> list = new ArrayList<String>();
    	for(int i=1; i<n+1; i++) {
    		str2 += i;
    	}
    	list =permutation(list, str2, "");
    	
    	int a = -1;
    	for(int i=0; i<list.size(); i++) {
    		if(list.get(i).equals(str)) {
    			a = i;
    			break;
    		}
    	}
    	if(a != 0) {
    		System.out.println(list.get(a - 1));
    	}
    	System.out.println(list.get(a));
    	if(a != list.size()-1) System.out.println(list.get(a + 1));
    }
	
    public static List<String> permutation(List<String> list, String q, String ans){
    	if(q.length() <= 1) {
    		list.add(ans + q);
    	}else {
    		for (int i = 0; i < q.length(); i++) {
    			permutation(list, q.substring(0, i) + q.substring(i + 1), ans + q.charAt(i) + " ");
    		}
    	}
    	return list;
    }    	
}