洛谷 1020:导弹拦截(DP,LIS)

题目描述

某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统。但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度。某天,雷达捕捉到敌国的导弹来袭。由于该系统还在试用阶段,所以只有一套系统,因此有可能不能拦截所有的导弹。

输入导弹依次飞来的高度(雷达给出的高度数据是 \le 50000≤50000 的正整数),计算这套系统最多能拦截多少导弹,如果要拦截所有导弹最少要配备多少套这种导弹拦截系统。

输入输出格式

输入格式:

1 行,若干个整数(个数 \le 100000≤100000 )

输出格式:

2 行,每行一个整数,第一个数字表示这套系统最多能拦截多少导弹,第二个数字表示如果要拦截所有导弹最少要配备多少套这种导弹拦截系统。

输入输出样例

输入样例#1: 复制

389 207 155 300 299 170 158 65

输出样例#1: 复制

6
2

说明

为了让大家更好地测试n方算法,本题开启spj,n方100分,nlogn200分

每点两问,按问给分

思路

求需要多少套拦截系统就是求一个数组中的最大上升子序列。求能够拦截多少导弹就是倒序求该数组的最长上升子序列

AC代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#define ll long long
#define ms(a) memset(a,0,sizeof(a))
#define pi acos(-1.0)
#define INF 0x3f3f3f3f
const double E=exp(1);
const int maxn=1e6+10;
using namespace std;
int a[maxn];
int b[maxn];
int dp[maxn];
int DP[maxn];
int main(int argc, char const *argv[])
{
	ios::sync_with_stdio(false);
	int k=0;
	while(~scanf("%d",&a[k++]));
	k-=1;
	dp[0]=a[0];
	int pos;
	int ans=1;
	int sum=1;
	//求需要多少拦截系统
	for(int i=0;i<k;i++)
	{
		b[k-i-1]=a[i];
		pos=lower_bound(dp,dp+sum,a[i])-dp;
		dp[pos]=a[i];
		sum=max(sum,pos+1);
	}
	int Pos;
	DP[0]=b[0];
	//求一个系统最多能拦截多少导弹
	for(int i=1;i<k;i++)
	{
		Pos=upper_bound(DP,DP+ans,b[i])-DP;
		DP[Pos]=b[i];
		ans=max(ans,Pos+1);
	}
	printf("%d\n%d\n",ans,sum);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wang_123_zy/article/details/81265266