[蓝桥杯]真题讲解:飞机降落(DFS枚举)

一、视频讲解

视频讲解
在这里插入图片描述

二、暴力代码(也是正解代码)

//飞机降落: 暴力枚举DFS
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 10 + 20;

struct plane{
	int t, d, l;
}p[N];

bool st[N];//判断当前飞机是否已经降落

int n;//飞机个数。

//u表示已经有U架飞机成功降落了。
//time表示当前的时间,前一架飞机落地的时间。
bool dfs(int u, int time)
{
	if(u >= n)
		return true;

	//考虑第(u + 1)架飞机谁落。
	for(int i = 0; i < n; i ++)
	{
		if(!st[i])
		{
			st[i] = true;
			if(p[i].t + p[i].d < time)
			{
				//回溯,回溯到DFS之前的状态。
				st[i] = false;
				return false;
			}
			
			int t = max(time, p[i].t) + p[i].l;
			if(dfs(u + 1, t))
				return true;
			
			//回溯,回溯到DFS之前的状态。
			st[i] = false;
		}
	}
	return false;
}

void solve()
{
	cin >> n;
	for(int i = 0; i < n; i ++)
		cin >> p[i].t >> p[i].d >> p[i].l;

	if(dfs(0, 0))
		cout << "YES" << endl;
	else
		cout << "NO" << endl;
		
	for(int i = 0; i < n; i ++)
	    st[i] = false;
}	

signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	int t = 1;
	cin >> t;
	while(t--)
	solve();
}
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐