最长递增子序列LIS(动态规划+二分查找)

/*
* =====================================================================================
*
*       Filename:  LIS.c
*
*    Description:  求数组的最长递增子序列的长度(Longest Inceasing SubSequence: LIS)
*                  该题目最好的时间复杂度为O(nlogn), 做法参见http://www.felix021.com/blog/read.php?1587,
*                                      使用到了动态规划
*        Version:  1.0
*        Created:  2010年08月27日 11时11分01秒
*       Revision:  none
*       Compiler:  gcc
*
*         Author:  glq2000 (), [email protected]
*        Company:  HUE ISRC
*
* =====================================================================================
*/


#include 
#include 
#include 

#define N 9 //数组元素个数
int array[N] = {2, 1, 6, 3, 5, 4, 8, 7, 9}; //原数组
int B[N]; //在动态规划中使用的数组,用于记录中间结果,其含义三言两语说不清,请参见博文的解释
int len; //用于标示B数组中的元素个数

int LIS(int *array, int n); //计算最长递增子序列的长度,计算B数组的元素,array[]循环完一遍后,B的长度len即为所求
int BiSearch(int *b, int len, int w); //做了修改的二分搜索算法

int main()
{
        printf("LIS: %d\n", LIS(array, N));

        int i;
        for(i=0; i B[len-1])
                {
                        B[len] = array[i];
                        ++len;
                }
                else
                {
                        pos = BiSearch(B, len, array[i]);
                        B[pos] = array[i];
                }
        }

        return len;
}


//做了修改的二分搜索算法,若要查找的数w在长为len的数组b中存在则返回下标,
//若不存在,则返回b数组中的刚刚大于w的那个元素的下标,该元素即需要被替换的元素
int BiSearch(int *b, int len, int w)
{
        int left = 0, right = len-1;
        int middle;
        while(left <= right)
        {
                middle = (left+right)/2;
                if(b[middle] > w)
                        right = middle - 1;
                else if(b[middle] < w)
                        left = middle + 1;
                else
                        return middle;
        }

        return (b[middle]>w) ? middle : middle+1; //即返回b数组中的刚刚大于w的那个元素的下标
}

以下解法为传统解法,时间复杂度为O(n2):

// Longest_Increase_subsequence.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include 
#include 
#include "windows.h"
/**
* Description: Calulate the longest increase subsequence
*@param s1, source sequence
*@param s2, output, longest increase sequence
*/
template void longest_increase_subsequence(const std::vector& s1, std::vector& s2)
{
	
	int n = s1.size(); if (n<1) return;
	int m = 0;
	int k = 0;
	std::vector b(n+1, 1);
	std::vector p(n+1, 0);
			
	for (int i=1;i<=n;i++)	
	{
		for (int j=1;j s1[j-1] && b[i] < b[j] +1 )
			{
				b[i] = b[j] + 1;
				p[i] = j;
			}	
		}
	}	
	for ( int i=1;i<=n;i++)
	{
		if (m0)
	{
		s2[m-1] = s1[k-1];
		m--;
		k = p[k];
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	int a[] = { 1, 9, 3, 8, 11, 4, 5, 6, 4, 19, 7, 1, 7 };
	std::vector seq(a, a+sizeof(a)/sizeof(a[0]));
	std::vector r;
	longest_increase_subsequence(seq, r);
	for (int i=0;i


你可能感兴趣的:(C++,数据结构与算法)