题目链接:This is the link
题目描述
某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统。但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能高于前一发的高度。某天,雷达捕捉到敌国的导弹来袭。由于该系统还在试用阶段,所以只有一套系统,因此有可能不能拦截所有的导弹。
输入导弹依次飞来的高度(雷达给出的高度数据是 \le 50000≤50000 的正整数),计算这套系统最多能拦截多少导弹,如果要拦截所有导弹最少要配备多少套这种导弹拦截系统。
输入输出格式
输入格式:
11 行,若干个整数(个数 \le 100000≤100000 )
输出格式:
22 行,每行一个整数,第一个数字表示这套系统最多能拦截多少导弹,第二个数字表示如果要拦截所有导弹最少要配备多少套这种导弹拦截系统。
输入输出样例
输入样例#1:
389 207 155 300 299 170 158 65
输出样例#1:
6
2
说明
为了让大家更好地测试n方算法,本题开启spj,n方100分,nlogn200分
每点两问,按问给分
题目思路:最长不上升子序列(下降<=)长度就是最大拦截导弹数,最长上升子序列的长度就是需要的系统数量。
//本题需要使用二分方法计算(即nlogn)的算法
好了直接上代码:
This is the code
#include<bits/stdc++.h>
using namespace std;
const int maxn=100001;
int ans1,ans2;
int dp[maxn];
int s[maxn];//储存导弹高度
int search1(int m,int x)//最长不上升子序列的二分寻找
{
int l=1,r=m;
int mid;
while(l<=r)
{
mid=(l+r)/2;
if(dp[mid]>=x)//注意判断条件
l=mid+1;
else
r=mid-1;
}
return l;
}
int search2(int m,int x)//最长上升
{
int l=1,r=m;
int mid;
while(l<=r)
{
mid=(l+r)/2;
if(dp[mid]<x)//注意判断条件
l=mid+1;
else
r=mid-1;
}
return l;
}
void pd(int n)
{
dp[1]=s[1];
ans1=1;
for(int i=2;i<=n;++i)
{
if(s[i]<=dp[ans1])
dp[++ans1]=s[i];
else
dp[search1(ans1,s[i])]=s[i];
}
memset(dp,0,sizeof(dp));
dp[1]=s[1];
ans2=1;
for(int i=2;i<=n;++i)
{
if(s[i]>dp[ans2])
dp[++ans2]=s[i];
else
dp[search2(ans2,s[i])]=s[i];
}
}
int main()
{
int temp;
int n=0;
while(cin>>temp)
s[++n]=temp;
pd(n);
cout<<ans1<<endl<<ans2;
return 0;
}
emmmmmm下面是大声用stl的做法:
原博客网址:https://528hby.blog.luogu.org/solution-p1020
#include<bits/stdc++.h>
using namespace std;
int a[100005],f[100005],l[100005];
struct cmp//重载
{
bool operator()(int a,int b)
{
return a>b;
}
};
int main()
{
int n=1;
while(cin>>a[n])n++;
n--;
int con=1,cont=1;
l[1]=f[1]=a[1];
for(int i=2;i<=n;i++)
{
if(l[cont]>=a[i])l[++cont]=a[i];//最长不下降
else l[upper_bound(l+1,l+cont+1,a[i],cmp())-l]=a[i];
if(f[con]<a[i])f[++con]=a[i];//最长上升
else f[lower_bound(f+1,f+con+1,a[i])-f]=a[i];
}
cout<<cont<<" "<<con;
return 0;
}