7 IN 1 1 IN 1 2 OUT 1 OUT 2 IN 2 1 OUT 2 OUT 1 2 IN 1 1 OUT 1
2 EMPTY 3 1 1
代码:(代码里面有详解,具体思路,题目已经给的够清楚了)
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
ArrayList<patient> list = new ArrayList<patient>(); //利用ArrayList来实现病人先来先服务,不过题目要求优先级高的先看病,后面取病人编号时有条件控制的
int n = sc.nextInt(); //接收发生事件的数目
sc.nextLine(); //这里要注意,因为sc.nextInt()不会接收后面的回车符,所以这里一定要接收回车符,不然会影响后面的数据接收
int num=1; //用来表示病人编号
while (n-- > 0) {
String str = sc.nextLine(); //接收发生事件
String[] strs = str.split(" "); //因为中间有空格隔开,所以直接用空格分隔字符串为字符串数组
//如果是需要看医生的就和”IN“匹配,如果匹配成功则把病人信息加入到list的最后面,如果不是,那个就是和”OUT“匹配了,就进行else后面的操作
if (strs[0].compareTo("IN") == 0) {
//根据题意:分割后的strs[]数组,第一个(strs[0])是IN,第二个(strs[1])是病人要求的医生的编号,第一个(strs[1])是病人优先级
patient p = new patient(num++,strs[1], strs[2]);
list.add(p);
} else {
//如果链表为空,表示没有病人,就不可可能OUT,所以直接输出"EMPTY";否则进行else里面的操作(这里看似多此一举,但是能快速处理空链表时的情况)
if (list.isEmpty()) {
System.out.println("EMPTY");
} else {
//根据题意:分割后的strs[]数组,第一个(strs[0])是OUT,第二个(strs[1])是该医生进行一次诊治
int out = -1; //用来保存优先级,初始化优先级最低
int outIndex=0;//用来保存要输出的那个病人在list里面的位置
boolean flag = false; //用来控制如果没有该医生需要处理的病,就不动,有的话变为true,方便后面输出
//遍历list链表
for (int i = 0; i < list.size(); i++) {
//条件:先匹配到该医生需要处理的病人是否有;该医生需要处理的病人的优先级比其他病人的优先级都要高
if (list.get(i).getDoctor().compareTo(strs[1]) == 0&& Integer.parseInt(list.get(i).getPriority()) > out) {
out = Integer.parseInt(list.get(i).getPriority()); //把满足要求的病人的优先级赋值给out
outIndex=i; //把满足要求的病人在list里面的位置赋值给outIndex
flag = true;
}
}
//如果有该医生需要处理的病人则输出病人编号;否则输出"EMPTY"
if (flag) {
System.out.println(list.remove(outIndex).getNum());
flag = false;
} else {
System.out.println("EMPTY");
}
}
}
}
}
}
}
//patient类,这是我用来封装病人的编号,需要的医生的编号,和优先级的类
class patient {
private int num; //编号
private String doctor = null;//医生的编号这里就是(1,2,3)
private String Priority = null; //优先级(根据题目给的)
//构造函数
public patient(int num, String doctor, String priority) {
this.num = num;
this.doctor = doctor;
Priority = priority;
}
public int getNum() { //获取病人编号
return num;
}
public String getDoctor() { //获取医生编号
return doctor;
}
public String getPriority() { //获取优先级
return Priority;
}
}