简体   繁体   English

显示最长的递增子序列

[英]display the longest increasing subsequence

#include<iostream>
using namespace std;
int main()
{
    int a[]={0,8,4,12,2,10,6,1,9,5,13,3,11,7};
    int b[50],i,j,n,ls[50];
    n=sizeof(a)/sizeof(a[0]);
    int maxlen=0,end=-1;
    b[0]=-1;
    for(i=0;i<n;i++)
    {
        ls[i]=1;
        for(j=0;j<i;j++)
        {
            if(a[i]>a[j] && ls[i]<ls[j]+1)
            {
                ls[i]=ls[j]+1;
                b[i]=j;
            }
        }
        if(ls[i]>maxlen)
        {
            end=i;
            maxlen=ls[i];
        }
    }

    cout<<maxlen<<endl;
    for(int k=end;b[k]!=-1;k=b[k])
    {
        cout<<a[k];
    }
            return 0;
}

This was the program I done for finding the longest increasing subsequence. 这是我为找到最长的递增子序列所做的程序。 I am getting the length of the subsequence correctly but i am not getting the sequence correctly. 我正确地获得了子序列的长度,但是我没有正确地获得了序列。 I think there may be a problem with the the last for loop which contains the variable k , but I cant figure it out. 我认为包含变量k的last for循环可能存在问题,但我无法弄清楚。 please help me. 请帮我。

Actually you wrote correct sequence but in reverse order and skipping the first(last) element 实际上,您编写了正确的序列,但是顺序相反,并跳过了first(last)元素

You may change the last for to include the first element 您可以将最后一个更改为包含第一个元素

vector<int> v;
for(int k=end;k!=-1;k=b[k])
{
    cout << a[k] << ' ';
}

You may need to store element in something like std::vector to reverse it to get correct order 您可能需要将元素存储在类似std::vector类的元素中以将其反转以获取正确的顺序

vector<int> v;
for(int k=end;k!=-1;k=b[k])
{
    v.push_back(a[k]);
}
reverse(v.begin(), v.end());
for(int x: v) {
    cout << x << ' ';
}

http://ideone.com/URPACA http://ideone.com/URPACA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM