LIS

/*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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值