有家动物收容所只收留猫和狗,但有特殊的收养规则。
收养人有两种收养方式:
第一种为直接收养所有动物中最早进入收容所的。
第二种为选择收养的动物类型(猫或狗),并收养该种动物中最早进入收容所的。给定一个操作序列int[][2] ope代表所有事件。
若第一个元素为1,则代表有动物进入收容所,第二个元素为动物的编号,正数代表狗,负数代表猫;
若第一个元素为2,则代表有人收养动物,第二个元素若为0,则采取第一种收养方式(最早),若为1,则指定收养狗,若为-1则指定收养猫。
请按顺序返回收养的序列。
import java.util.*;
public class CatDogAsylum {
public static ArrayList<Integer> asylum(int[][] ope) {
Queue<Integer> Dog = new LinkedList<>();//狗 +
Queue<Integer> Cat = new LinkedList<>();//猫 -
Queue<Integer> All = new LinkedList<>();//所有
Queue<Integer> ToAll = new LinkedList<>();//用于All中间元素处出队后恢复原顺序
ArrayList<Integer> list = new ArrayList<>();//收养序列
for (int i = 0; i < ope.length; i++) {
if(ope[i][0] == 1) {//代表有动物进收容所
All.offer(ope[i][1]);
if(ope[i][1] > 0){//进入收容所的是狗
Dog.offer(ope[i][1]);
}else if(ope[i][1] < 0){//代表进入收容所的是猫
Cat.offer(ope[i][1]);
}
}else if(ope[i][0] == 2){//代表有动物被收养
if(ope[i][1] == 0){//表示采取第一种收养方式
if(!All.isEmpty()){
Integer tmp = All.poll();
list.add(tmp);
if(tmp.equals(Dog.peek())){
Dog.poll();
}else if (tmp.equals(Cat.peek())){
Cat.poll();
}
}else {
return list;
}
}else if(ope[i][1] == 1){//收养狗
if(!Dog.isEmpty()){
Integer tmp = Dog.poll();
list.add(tmp);
for (int j = 0; j < All.size();) {
if(All.peek().equals(tmp)){
All.poll();
break;
}else {
ToAll.offer(All.poll());
}
}
int size = All.size();
for (int k = ToAll.size(); k > 0 ; k--) {
All.offer(ToAll.poll());
}
for (int j = 0; j < size; j++) {
All.offer(All.poll());
}
}
}else if(ope[i][1] == -1){//收养猫
if(!Cat.isEmpty()){
Integer tmp = Cat.poll();
list.add(tmp);
int size = All.size();
for (int j = 0; j < size; j++) {
if(All.peek().equals(tmp)){
All.poll();
break;
}else {
ToAll.offer(All.poll());
}
}
size = All.size();
for (int k = ToAll.size(); k > 0 ; k--) {
All.offer(ToAll.poll());
}
for (int j = 0; j < size; j++) {
All.offer(All.poll());
}
}
}
}
}
return list;
}
public static void main(String[] args) {
int[][] ope ={{1,-3},{1,-6},{1,10},{1,3},{2,0},{1,19},{2,-1},
{1,-81}, {1,36},{2,0},{2,1},{1,66},{2,0},{1,-13},{2,0},
{2,-1},{2,0},{1,29},{2,1},{2,1},{2,1},{1,56},{1,-99},{2,-1},{2,-1}};
System.out.print("收养序列:");
System.out.println(asylum(ope));
}
}
运行结果如下: