题目贴在最后。
思路:
借助栈。建5个栈,分别保存1~5的任务序号,由于每次取编号最大的,所以只需弹出栈顶元素即可。
代码:
// 本题为考试多行输入输出规范示例,无需提交,不计分。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i ++) {
arr[i] = scanner.nextInt();
}
Deque<Integer> stack1 = new LinkedList<>();
Deque<Integer> stack2 = new LinkedList<>();
Deque<Integer> stack3 = new LinkedList<>();
Deque<Integer> stack4 = new LinkedList<>();
Deque<Integer> stack5 = new LinkedList<>();
for(int i = 0; i < n; i ++) {
if (arr[i] == 1) {
stack1.offerLast(i + 1);
}
if (arr[i] == 2) {
stack2.offerLast(i + 1);
}
if (arr[i] == 3) {
stack3.offerLast(i + 1);
}
if (arr[i] == 4) {
stack4.offerLast(i + 1);
}
if (arr[i] == 5) {
stack5.offerLast(i + 1);
}
if (!stack1.isEmpty() && !stack2.isEmpty() && !stack3.isEmpty() &&
!stack4.isEmpty() && !stack5.isEmpty()) {
System.out.println(stack1.pollLast() + " " + stack2.pollLast() + " " +
stack3.pollLast() + " " + stack4.pollLast() + " " + stack5.pollLast());
}
else {
System.out.println(-1);
}
}
}
}