CCF 201709-2 公共钥匙盒

15 篇文章 0 订阅

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+" ");
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值