/*Problem:
Longest increment sequence*/
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 100
#define _INF -0x7FFFFFFF
/*
Display the longest increment sequence
@s: longest increment sequence
@n: maximum length of s
*/
void dispS(int * s,int n){
int i;
for(i=0; i<n&&s[i]!=_INF ;i++)
printf("%d\t",s[i]);
putchar(10);
}
/*
Assemble s
@seq: sequence
@s: will be longest increment sequence
@L: length of s
@pre: pre-element position array
@p: current element position
*/
void pushS(int * seq,int * s,int L,int * pre,int p)
{
int i=L-1;
while(i>=0){
s[i--] = seq[p];
p = pre[p];
}
}
/*
args:
@seq: sequence of input array
@n: the length of sequence
@s: for longest increment sequence
*/
int LIS(int * seq,int n,int * s)
{
int b[MAX_LEN]={0}; //Record longest length from element (0) to (n-1)
int pre[MAX_LEN] = {-1};//Record pre-element position,default set to -1,it's the end mark of search back
int i,j;
b[0] = 1; //Set minimum length is 1;
for(i=1; i<n ;i++){
int k = 0; //Record temp longest length of b[j](=b[i-1])
for(j=0; j<i ;j++){
//From j = 0 to i-1,if element seq[i] is bigger than seq[j],and at the same time
//current k is smaller than b[j],modify k and record pre-element of i is j;
if(seq[i]>seq[j]&&k<b[j]){
k=b[j];
pre[i] = j;
}
}
b[i] = k + 1;
}
//To this step,have get all the length of possible b[i];
//Now,calculate the biggest b[i]'s positon
int m = 0;
for(i=1; i<n ;i++){
// printf("%d\t",b[i]);
if(b[i]>b[m])
m = i;
}
pushS(seq,s,b[m],pre,m); //Record the longest increment sequence
return b[m]; //Return the longest length
}
/***************************Main()*****************************/
int main(int argc, char *argv[])
{
int n = 9;
int a[9] = {8,65,158,170,155,239,300,207,389};
//The return sequence
int s[9];
int i;
for(i=0; i<n ;i++)s[i]=_INF;
printf("\nL:%d\n",LIS(a,n,s));
dispS(s,n);
putchar(10);
system("PAUSE");
return 0;
}
LIS
最新推荐文章于 2018-03-28 13:05:51 发布