题目描述
问题描述
某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统。但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度。某天,雷达捕捉到敌国的导弹来袭。由于该系统还在试用阶段,所以只有一套系统,因此有可能不能拦截所有的导弹。
输入导弹依次飞来的高度(雷达给出的高度数据是不大于30000的正整数),计算这套系统最多能拦截多少导弹,如果要拦截所有导弹最少要配备多少套这种导弹拦截系统。
输入格式
一行,为导弹依次飞来的高度
输出格式
两行,分别是最多能拦截的导弹数与要拦截所有导弹最少要配备的系统数
样例输入
389 207 155 300 299 170 158 65
样例输出
6
2
题解:
思路: 动态规划dp
- 求最多能拦截的导弹数,也就是只有一个该系统,这个系统最多可以拦截多少,比如样例,可以这样拦截:389、300、299、170、158、65,其实也就是求最长非递增(后面的<=前面的)子序列,最后选出以某一个数结尾(dp1[i])的最长的非子序列长度。
- 求最少需要配备的系统数,这个说是用贪心的思想,但是我并不是很理解,这里的解法参考了别人的:求最长递增子序列,最后选出以某一个数结尾(dp2[i])的最长的递增子序列长度
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n = 0;
int h[MAX];
int dp1[MAX];// 求最长非递增(即<=)子序列(求最多能拦截多少导弹)
int dp2[MAX];// 求(求所有导弹最少要配备的系统数)
int main()
{
/*
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
*/
int x;
while(cin >> x)
{
h[n++] = x;
}
for(int i = 0; i < n; i++)
{
dp1[i] = dp2[i] = 1;
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= i-1; j++)
{
// 求最长非递增(即<=)子序列(求最多能拦截多少导弹)
if(h[i] <= h[j])
{
dp1[i] = max(dp1[i],dp1[j]+1);
}
// 求最长递增子序列(求最多要多少个系统)
if(h[i] > h[j])
{
dp2[i] = max(dp2[i],dp2[j]+1);
}
}
}
int res1 = -inf;
int res2 = -inf;
for(int i = 0; i < n; i++)
{
res1 = max(res1,dp1[i]);
res2 = max(res2,dp2[i]);
}
cout << res1 << endl << res2 << endl;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)