187. 导弹防御系统

题目链接

187. 导弹防御系统

为了对抗附近恶意国家的威胁,R 国更新了他们的导弹防御系统。

一套防御系统的导弹拦截高度要么一直 严格单调 上升要么一直 严格单调 下降。

例如,一套系统先后拦截了高度为 3 和高度为 4 的两发导弹,那么接下来该系统就只能拦截高度大于 4 的导弹。

给定即将袭来的一系列导弹的高度,请你求出至少需要多少套防御系统,就可以将它们全部击落。

输入格式

输入包含多组测试用例。

对于每个测试用例,第一行包含整数 n,表示来袭导弹数量。

第二行包含 n 个不同的整数,表示每个导弹的高度。

当输入测试用例 n=0 时,表示输入终止,且该用例无需处理。

输出格式

对于每个测试用例,输出一个占据一行的整数,表示所需的防御系统数量。

数据范围

1n50

输入样例:

5 3 5 2 4 1 0

输出样例:

2

样例解释

对于给出样例,最少需要两套防御系统。

一套击落高度为 3,4 的导弹,另一套击落高度为 5,2,1 的导弹。

解题思路

dfs,迭代加深

数据范围比较小,另外这里可上升可下降,不能用 LIS 来做,可考虑暴搜,但由于求最少,可用迭代加深来优化,另外需要注意dfs的写法,放置某个导弹时,以上升序列为例,贪心思想,即放置在比当前导弹高度低且最大的序列后,但由于如果都没找到的话即当前导弹高度是最低的,即该序列单调下降的,从前枚举找到的第一个即为符合贪心策略的位置,下降序列同理

  • 时间复杂度:O(n×2n)

代码

// Problem: 导弹防御系统 // Contest: AcWing // URL: https://www.acwing.com/problem/content/189/ // Memory Limit: 64 MB // Time Limit: 3000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> //#define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } const int N=55; int n,h[N],up[N],down[N]; bool dfs(int u,int su,int sd,int depth) { if(sd+su>depth)return false; if(u==n)return true; bool f=true; for(int i=0;i<su;i++) if(h[u]>up[i]) { int t=up[i]; up[i]=h[u]; if(dfs(u+1,su,sd,depth))return true; up[i]=t; f=false; break; } if(f) { up[su]=h[u]; if(dfs(u+1,su+1,sd,depth))return true; } f=true; for(int i=0;i<sd;i++) if(h[u]<down[i]) { int t=down[i]; down[i]=h[u]; if(dfs(u+1,su,sd,depth))return true; down[i]=t; f=false; break; } if(f) { down[sd]=h[u]; if(dfs(u+1,su,sd+1,depth))return true; } return false; } int main() { while(scanf("%d",&n),n) { for(int i=0;i<n;i++)scanf("%d",&h[i]); int depth=0; while(!dfs(0,0,0,depth))depth++; printf("%d\n",depth); } return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/15954557.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(47)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示