zoukankan      html  css  js  c++  java
  • 最长递增子序列

    1. 动态规划,使用一个数组保存当前的最大递增子序列长度,时间复杂度为O(N^2)

    # include <iostream>
    # include <cstdlib>
    # include <climits>
    using namespace std;
    
    int longestsub(int a[],int n)
    {
    	int *dis=(int *)malloc((n+1)*sizeof(int));
    	dis[0]=1;
    	int i,j;
    	for(i=0;i<n;i++)
    		dis[i]=1;
    	for(i=0;i<n;i++)
    	{
    	for(j=i-1;j>=0;j--)
    	{
    	if(a[i]>a[j]&&dis[i]<dis[j]+1)
    	{
    	dis[i]=dis[j]+1;
    	}
    	}
    	}
    	int ans=-1;
    	for(i=0;i<n;i++)
    		ans=max(ans,dis[i]);
    	free(dis);
    	return ans;
    }
    
    int main()
    {
    	int a[5]={3,6,5,4,7};
    	cout<<longestsub2(a,5)<<endl;
        system("pause");
        return 0;
    }

    2.《编程之美》上提供了第二种解法。使用数组b[len-1]表示长度为len时最后一个元素值,在这样的解法中能够使用二分查找使得程序加速,时间复杂度变为O(N*logN)

    # include <iostream>
    # include <cstdlib>
    # include <climits>
    using namespace std;
    
    int binsearch(int a[],int n,int target)  //binarysearch
    {
    int low=0;
    int high=n-1;
    int mid;
    while(low<=high)
    {
    mid=(high-low)/2+low;
    if(a[mid]==target)
    	return mid;
    else if(a[mid]<target)
    	low=mid+1;
    else 
    	high=mid-1;
    }
    return low;
    }
    
    int longestsub2(int a[],int n)
    {
    	int i=0;
    	int len=1;
    	int *b=(int *)malloc((n+1)*sizeof(int));
    	b[0]=a[0];
    	for(i=1;i<n;i++)
    	{
    	if(a[i]>b[len-1])
    	{
    	b[len]=a[i];
    	len++;
    	}
    	else 
    	{
    	int tmp=binsearch(a,n,a[i]);
    	b[tmp]=a[i];
    	}
    	}
    	free(b);
    	return len;
    }
    
    int main()
    {
    	int a[5]={7,6,8,4,1};
    	cout<<longestsub2(a,5)<<endl;
        system("pause");
        return 0;
    }


  • 相关阅读:
    ACM ICPC 2008–2009 NEERC MSC A, B, C, G, L
    POJ 1088 滑雪 DP
    UVA 11584 最短回文串划分 DP
    POJ 2531 Network Saboteur DFS+剪枝
    UVa 10739 String to Palindrome 字符串dp
    UVa 11151 Longest Palindrome 字符串dp
    UVa 10154 Weights and Measures dp 降维
    UVa 10271 Chopsticks dp
    UVa 10617 Again Palindrome 字符串dp
    UVa 10651 Pebble Solitaire 状态压缩 dp
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7090802.html
Copyright © 2011-2022 走看看