最长上升子序列输出序列贪心做法

之前做过的最长上升子序列的题只是不需要输出这个序列http://www.cnblogs.com/Scale-the-heights/p/4333346.html

做法就是从左到右扫一遍,可以参见http://blog.csdn.net/shuangde800/article/details/7474903

要输出路径其实也很简单,就开个数组f[]把所有数字在最长上升子序列中第一次出现的位置记录下来,然后逆序遍历,比如我们找到最长上升子序列的长度为n,则我们从后往前找到曾经在最长上升子序列中位置为n的数字储存起来,由于扫描是从后往前的,所以这个数字一定是原序列的一个最长上升子序列中位置为n的数字。以此类推。

详细解释可以参见http://blog.csdn.net/ouckitty/article/details/27801843

我是用lower_bound代替了二分,时间紧迫,没时间详写了,要想详解的可以看下上面的链接,贴个代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
int num[1000010],tmp[1000010],f[1000010];
int main()
{
    int t;
    scanf("%d",&t);
    getchar();
    getchar();
    while(t--){
        int cnt=1;
        string str;
        while(getline(cin,str)){
            int len=str.length();
            if(len==0){
                break;
            }
            int ans=0;
            for(int i=0;i<len;i++){
                ans=10*ans+(str[i]-'0');
            }
            num[cnt++]=ans;
        }
        int s=0;
        for(int i=1;i<cnt;i++){
            if(s==0){
                tmp[s++]=num[1];
                f[1]=0;
            }
            else{
                if(num[i]>tmp[s-1]){
                    f[i]=s;
                    tmp[s++]=num[i];
                }
                else{
                    int low=lower_bound(tmp,tmp+s,num[i])-tmp;
                    if(low<s){
                        tmp[low]=num[i];
                        f[i]=low;
                    }
                }
            }
        }
        cout<<"Max hits: "<<s<<endl;
        int x=s;
        int counter=0;
        for(int i=cnt-1;i>=1;i--){
            if(f[i]==x-1){
                tmp[counter++]=num[i];
                x--;
            }
        }
        for(int i=counter-1;i>=0;i--){
            cout<<tmp[i]<<endl;
        }
        /*for(int i=0;i<s;i++){
            printf("%d\n",tmp[i]);
        }*/
        if(t){
            printf("\n");
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/Scale-the-heights/p/4429671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值