题目链接
https://www.acwing.com/problem/content/189/
题意
导弹只能打掉严格递增或者严格递减的一段序列,求覆盖n个目标需要多少导弹
思路
如果只看严格递增或者严格递减就是导弹拦截的贪心做法,因为有严格递增或者严格递减的限制,所以在外面套一个搜索的壳就行了,注意维护全局变量ans,以便剪枝
代码
#include<cstdio>
#include<iostream>
#include<iomanip>
#include<map>
#include<unordered_map>
#include<string>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define endl "\n"
//#define int long long
//#define double long double
using namespace std;
typedef long long ll;
const int maxn=55;
const int inf=0x3f3f3f3f;
int n,m;
int a[maxn];
int d1[maxn],d2[maxn];
int ans;
void dfs(int now,int up,int down){
if(up+down>=ans) return ;
if(now==n+1){
ans=up+down;
return ;
}
int k=0;
while(k<up&&d1[k]>=a[now]) k++;
int t=d1[k];
d1[k]=a[now];
if(k<up) dfs(now+1,up,down);
else dfs(now+1,up+1,down);
d1[k]=t;
k=0;
while(k<down&&d2[k]<=a[now]) k++;
t=d2[k];
d2[k]=a[now];
if(k<down) dfs(now+1,up,down);
else dfs(now+1,up,down+1);
d2[k]=t;
}
int main(){
IOS
while(cin>>n,n){
ans=n;
for(int i=1;i<=n;i++)
cin>>a[i];
dfs(1,0,0);
cout<<ans<<endl;
}
}