返回题解分享
讨论 / 题解分享/ 帖子详情

飞机降落(编程题) - 题解

注意回溯部分的代码,别忘了更新down的同时回退currentTime。

import java.util.Scanner;

public class Main {
	public static int T;
	public static boolean flag[]; // 第几组飞机能否落地成功
	public static boolean down[]; // 第几架飞机是否已经落地

	public static class Plane {
		int arriveTime;
		int hoverTime;
		int downTime;

		public Plane(int arriveTime, int hoverTime, int downTime) {
			super();
			this.arriveTime = arriveTime;
			this.hoverTime = hoverTime;
			this.downTime = downTime;
		}

		public Plane() {
			// TODO Auto-generated constructor stub
		}

	}

	// currentTime 当前时间
	// idx 已经降落idx - 1 架飞机了 ,现在判断第 idx 架飞机
	// total 该组飞机的总数
	// code 该组的编号
	public static void dfs(int currentTime, int idx, int total, int code, Plane plane[]) {
		if (idx > total) {
			flag[code] = true;
			return;
		}
		for (int i = 1; i <= total; i++) {
			if (!down[i]) {
				if (currentTime <= plane[i].arriveTime) {
					int gap = plane[i].arriveTime + plane[i].downTime - currentTime;
					currentTime += gap;
					down[i] = true;
					dfs(currentTime, idx + 1, total, code, plane);
					down[i] = false;
					currentTime -= gap;
				} else if (currentTime <= plane[i].arriveTime + plane[i].hoverTime) {
					currentTime += plane[i].downTime;
					down[i] = true;
					dfs(currentTime, idx + 1, total, code, plane);
					down[i] = false;
					currentTime -= plane[i].downTime;
				}
			}
		}
		return;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		T = sc.nextInt();
		flag = new boolean[T + 1];
		for (int i = 1; i <= T; i++) {
			int N = sc.nextInt(); // 该组飞机总数
			down = new boolean[N + 1];
			Plane plane[] = new Plane[N + 1];
			for (int j = 1; j <= N; j++) {
				int arriveTime = sc.nextInt();
				int hoverTime = sc.nextInt();
				int downTime = sc.nextInt();
				Plane currentPlane = new Plane(arriveTime, hoverTime, downTime);
				plane[j] = currentPlane;
			}
			dfs(0, 1, N, i, plane);
		}
		sc.close();
		for (int i = 1; i <= T; i++) {
			if (flag[i]) {
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		}
	}

}
0 回复 0 转发 0 喜欢 3 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!