Generate Least Derangement
int [ ] D = new int [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) { int d = PQ . peek ( ) ; PQ . remove ( ) ; if ( d != S [ i ] i == N ) { D [ i ] = d ; } else { D [ i ] = PQ . peek ( ) ; PQ . remove ( ) ; PQ . add ( d ) ; } } if ( D [ N ] == S [ N ] ) { int t = D [ N - 1 ] ; D [ N - 1 ] = D [ N ] ; D [ N ] = t ; }