(dp+dfs+贪心)acwing 187. 导弹防御系统

187. 导弹防御系统

题目链接https://www.acwing.com/problem/content/189/
在这里插入图片描述

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int a[1010];
int n;
int ans;
int up[1010], down[1010];
void dfs(int su, int sd, int u) {
    
    
	if (su + sd >= ans)
		return;
	if (u == n) {
    
    
		ans = su + sd;
		return;
	}
	//放进上升子序列中
	int i;
	for (i = 1; i <= su; i++) {
    
    
		if (a[u] > up[i])//贪心
			break;
	}
	int temp = up[i];
	up[i] = a[u];
	dfs(max(i, su), sd, u + 1);
	up[i] = temp;


	//放在下降序列中
	for (i = 1; i <= sd; i++) {
    
    
		if (a[u] < down[i])//贪心
			break;
	}
	temp = down[i];
	down[i] = a[u];
	dfs(su, max(i, sd), u + 1);
	down[i] = temp;
}
int main() {
    
    

	while (~scanf("%d", &n) && n) {
    
    
		for (int i = 0; i < n; i++)
			scanf("%d", &a[i]);
		ans = 500;
		memset(up, 0,sizeof(up));
		memset(down, 0, sizeof(down));
		dfs(0, 0, 0);
		cout << ans<<endl;

	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46028214/article/details/115272863