Skip to content

Instantly share code, notes, and snippets.

@lucasheriques
Created April 25, 2018 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasheriques/c1596cb1d1ab5224b7027a131e6e937a to your computer and use it in GitHub Desktop.
Save lucasheriques/c1596cb1d1ab5224b7027a131e6e937a to your computer and use it in GitHub Desktop.
atok
import java.util.*;
public final class StackSorting {
public static void resolve(int[] array, int n, int k) {
Stack<Integer> s = new Stack<>();
s.push(n+1);
int t = 1;
for (int i = 0; i < n; i++) {
if (i >= k) array[i] = s.peek() - 1;
s.push(array[i]);
while (!s.isEmpty() && s.peek() == t) {
s.pop();
t++;
}
}
if (!s.isEmpty()) System.out.println("-1");
else {
for (int i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int resultado;
String parametros[];
Scanner input = new Scanner(System.in);
String line;
// n: numero de elementos da permutação, k: elementos que me deram
int n, k;
line = input.nextLine();
parametros = line.split(" ");
n = Integer.parseInt(parametros[0]);
k = Integer.parseInt(parametros[1]);
line = input.nextLine();
parametros = line.split(" ");
int array[] = new int[n];
for (int i = 0; i < k; i++)
array[i] = Integer.parseInt(parametros[i]);
resolve(array, n, k);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment