Fancy Mouse
- -|||
呵呵~~经典动态规划题。当然,这题的数据规模不大,所以就算搜索也不会tle。当然,最好的办法还是动规。这里我用的是搜索+剪枝的办法。
仔细分析一下题目,求一套导弹系统能击落多少导弹就是问你这个数列中最长的不下降(降序)子序列。求要多少导弹系统才能击落所有导弹就是问你这个数列中最长的上升(升序)子序列。第二点我说明一下,一个数列必定存在升序子序列,这个序列里面的任何两个数(两颗导弹)不能被分在一起(被同一个导弹系统击落),而最长的升序子序列的长度就是需要导弹系统的数量。
所以,我优化以后的代码就是这个样子:
#include<iostream>
using namespace std;

#define MAX 20
void Missile(int current,int step,int index,int lastindex);
int height[MAX],MaxCount,t;
int main()
{
    
while(cin>>height[t++])
        
if(20==t) break;
    t
--;
    Missile(
0,0,0,-1);
    cout
<<MaxCount<<' ';
    MaxCount
=0;
    Missile(
0,1,0,-1);
    cout
<<MaxCount<<endl;
    
return 0;
}

void Missile(int current,int step,int index,int lastindex)//step=0:decrease,step=1:increase
{
    
if(current>MaxCount) MaxCount=current;
    
if(t==index)return;
    
if((index+1-current)<(t-MaxCount))
    
{
        index
++;
        Missile(current,step,index,lastindex);
        index
--;
    }

    
if(-1==lastindex || (step ? height[index]>=height[lastindex] : height[index]<=height[lastindex]))
    
{
        lastindex
=index++;
        Missile(
++current,step,index,lastindex);
    }

}
posted on 2005-08-21 12:10  Fancy Mouse  阅读(781)  评论(1编辑  收藏  举报