CCF 201709-2 公共钥匙盒
题目长度适中,要点突出,阅读时不能漏掉任何关键的信息点。隐藏的点是要找到时间的最终界限。题目要求多位老师在归还钥匙时按照钥匙号码升序排列,此处可以重写ArrayList中的compareTo方法,使用Collections.sort进行自定义排序后再依次放回钥匙。上满分代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static ArrayList<Teacher> teachersList = new ArrayList<>();
public static ArrayList<Teacher> borrowList = new ArrayList<>();
public static ArrayList<Teacher> returnList = new ArrayList<>();
public static class Teacher implements Comparable<Teacher>{
int keyNum = 0;
int start = 0;
int length = 0;
int end = 0;
Teacher(int keyNum, int start, int length){
this.keyNum = keyNum;
this.start = start;
this.length = length;
this.end = start+length;
}
@Override
public int compareTo(Teacher o) {
return this.keyNum-o.keyNum;
}
}
public static int[] borrowKey(int[] keyBox, ArrayList<Teacher> borrowList) {
for(Teacher t : borrowList) {
for(int i=0 ; i<keyBox.length ; i++) {
if(keyBox[i]==t.keyNum)
keyBox[i]=-1;
}
}
return keyBox;
}
public static int[] returnKey(int[] keyBox, ArrayList<Teacher> returnList) {
for(Teacher t : returnList) {
for(int i=0 ; i<keyBox.length ; i++) {
if(keyBox[i]==-1) {
keyBox[i]=t.keyNum;
break;
}
}
}
return keyBox;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] input = scanner.nextLine().split(" ");
int N = Integer.parseInt(input[0]);
int K = Integer.parseInt(input[1]);
int[] keyBox = new int[N];
for(int i=0 ; i<N ; i++) {
keyBox[i]=i+1;
}
int maxTime = 0;
for(int i=0; i<K ; i++) {
int keyNum = scanner.nextInt();
int start = scanner.nextInt();
int length = scanner.nextInt();
int end = start+length;
teachersList.add(new Teacher(keyNum,start,length));
if(end>maxTime)maxTime=end;
}
scanner.close();
for(int i=1; i<=maxTime; i++) {
for(Teacher t : teachersList) {
if(t.end==i)
returnList.add(t);
}
Collections.sort(returnList);
keyBox=returnKey(keyBox,returnList);
for(Teacher t : teachersList) {
if(t.start==i)
borrowList.add(t);
}
keyBox=borrowKey(keyBox,borrowList);
returnList.clear();
borrowList.clear();
}
for(int i : keyBox) {
System.out.print(i+" ");
}
}
}