题目链接:https://www.acwing.com/activity/content/problem/content/1264/1/
解题思路:
这道题目的第一个问题就是求最长下降子序列,直接用一个DP就可以了;
而对于第二个问题,问最少用多少个系统可以拦截所有的导弹,我刚还是的思路是不断地去求最长下降子序列,指导导弹被去完为止,但是后来我找到了这个思路的一个bug,然后想我们可以直接维护一个数组,数组里面就是各自系统中最小的导弹的高度,由于我们需要把所有的导弹都给截获,所以对于每一个导弹我们要么就是用一个新系统来截获,要么就使用正在使用中的一个导弹进行截获,然后最优的方法是用正在使用中的导弹系统中 高度大于并且最接近于当前导弹高度 的系统进行截获,如果没有这样的系统,就直接再启动一个系统;(我觉得第二个问题像贪心),然后我想到如果我们每次都直接用sort维护这个数组然后再使用二分觉得时间复杂度可能会比较高,但估计也不会超时,在这里我是用使用一个set来维护的。
代码:
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <set>
using namespace std;
const int maxn = 1e3 + 5;
int a[maxn], cnt;
int f[maxn], pre[maxn], num;
bool vis[maxn];
set<int> st;
int main(void) {
// freopen("in.txt", "r", stdin);
int tmp;
while(scanf("%d", &tmp) != EOF) a[++ cnt] = tmp;
for(int i = 1; i <= cnt; i ++) f[i] = 1;
for(int i = 2; i <= cnt; i ++)
for(int j = 1; j < i; j ++)
if(a[i] <= a[j]) f[i] = max(f[i], f[j] + 1);
int res = 0, sum = 0;
for(int i = 1; i <= cnt; i ++) res = max(res, f[i]);
int maxx = 0;
for(int i = 1; i <= cnt; i ++) {
if(st.empty() || maxx < a[i]) st.insert(a[i]);
else {
int x = *(lower_bound(st.begin(), st.end(), a[i]));
st.erase(x);
st.insert(a[i]);
}
maxx = max(maxx, a[i]);
}
printf("%d\n%d\n", res, st.size());
return 0;
}
总结:我发现对于这种dp类型的问题,似乎正确的答案都不会是一遍的最优子结构堆积而成的,我们需要同时考虑多种路径(系统),直接得到一个最优解。