Domanda

#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. please help me.

È stato utile?

Soluzione

Actually you wrote correct sequence but in reverse order and skipping the first(last) element

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top