最少拦截系统-贪心或最长上升子序列

来源:互联网 发布:淘宝男装毛衣 编辑:程序博客网 时间:2024/06/14 03:35
最少拦截系统
Time Limit: 1000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u

Submit Status

Description

某国为了防御敌国的导弹袭击,发展出一种导弹拦截系统.但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到达任意的高度,但是以后每一发炮弹都不能超过前一发的高度.某天,雷达捕捉到敌国的导弹来袭.由于该系统还在试用阶段,所以只有一套系统,因此有可能不能拦截所有的导弹. 
怎么办呢?多搞几套系统呗!你说说倒蛮容易,成本呢?成本是个大问题啊.所以俺就到这里来求救了,请帮助计算一下最少需要多少套拦截系统. 
 

Input

输入若干组数据.每组数据包括:导弹总个数(正整数),导弹依此飞来的高度(雷达给出的高度数据是不大于30000的正整数,用空格分隔) 
 

Output

对应每组数据输出拦截所有导弹最少要配备多少套这种导弹拦截系统. 
 

Sample Input

8 389 207 155 300 299 170 158 65
 

Sample Output

2
 

子序列:

#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;//动态分析/*  |    |       |    |       |    |       |   |            |   |                |                |                |                |                *///从右到左呈现递增趋势//运用最长上升子序列int a[3005];int dp[3005];int main(){int n;//freopen("D://imput.txt","r",stdin);while(~scanf("%d",&n)){    for(int i=1;i<=n;i++){        scanf("%d",&a[i]);    }    memset(dp,0,sizeof(dp));    int reco=1;    for(int i=1;i<=n;i++){        dp[i]=1;        for(int j=1;j<i;j++){            if(a[j]<a[i]){                dp[i]=max(dp[i],dp[j]+1);            }        }        reco=max(reco,dp[i]);    }    printf("%d\n",reco);}return 0;}


贪心:

#include <cstdio>#include <cstring>#include <algorithm>int a[3005],dp[3005],keep[3005];//贪心算法,每个阶段寻找最优解(正解时间比动态规划要少空间消耗更大)using namespace std;int main(){    int cur=1,res=0,rec,reco,n;    //freopen("D://output.txt","r",stdin);    while(~scanf("%d",&n)){    if(n==0)continue;    scanf("%d",&a[1]);reco=cur=keep[1]=dp[1]=1;    for(int i=2;i<=n;i++){        scanf("%d",&a[i]);rec=0;        for(int k=1;k<=cur;k++){          if(a[res=keep[k]]>=a[i])        dp[i]=dp[rec||a[rec]>a[res]? res:rec=res];//将导弹加在最低数的尾部        }        if(a[rec]<a[i])  keep[dp[i]=++cur]=i;        else  keep[dp[i]=dp[rec]]=i;        reco=max(reco,dp[i]);//比较,得出最多系统        //printf("[%d]\n",dp[i]);    }    printf("%d\n",reco);    }return 0;}


1 0