最长递增子序列 lcs
2016-09-11 20:32
239 查看
题目传送门: https://www.51nod.com/onlineJudge/submitList.html#!userId=11254&problemId=1134
给出长度为N的数组,找出这个数组的最长递增子序列。(递增子序列是指,子序列的元素是递增的)
例如:5 1 6 8 2 4 5 10,最长递增子序列是1 2 4 5 10。(50000个数)
如果简单用dp递归的话,时间复杂度为o(n^2),肯定T了
查了题解后学到了一种优化版dp,时间复杂度是o(nlogn)
从头开始遍历,将不同长度的最大数字按照数列长度的大小储存起来,然后每次都用二分查找,找到不小于这个元素的第一个数字的位置,替换该数字
参考博客: http://blog.csdn.net/joylnwang/article/details/6766317
代码如下:
给出长度为N的数组,找出这个数组的最长递增子序列。(递增子序列是指,子序列的元素是递增的)
例如:5 1 6 8 2 4 5 10,最长递增子序列是1 2 4 5 10。(50000个数)
如果简单用dp递归的话,时间复杂度为o(n^2),肯定T了
查了题解后学到了一种优化版dp,时间复杂度是o(nlogn)
从头开始遍历,将不同长度的最大数字按照数列长度的大小储存起来,然后每次都用二分查找,找到不小于这个元素的第一个数字的位置,替换该数字
参考博客: http://blog.csdn.net/joylnwang/article/details/6766317
代码如下:
#include <iostream> #include <algorithm> #include <cstring> #include <stdio.h> #include <string> #include <cmath> #define ll long long #define mem(name,value) memset(name,value,sizeof(name)) #define mod 1000000007 #define PI 3.1415926 #define E 2.718281828459 using namespace std; const int maxn = 50005; int main() { int n; int a[maxn]; int dp[maxn]; mem(dp,0); cin >> n; for(int i=0;i<n;i++){ cin >> a[i]; } int len = 0; for(int i=0;i<n;i++){ int x = (lower_bound(dp,dp+len,a[i]) - dp); if(x == len) dp[len++] = a[i]; else dp[x] = a[i]; } int mx = 0; cout << len<< endl; return 0; }
相关文章推荐
- 最长公共子序列(LCS)和最长递增子序列(LIS)的求解
- 最长递增子序列(LCS)
- 算法系列笔记6(动态规划—最长公共子序列/串lcs和最长递增子序列(LIS))
- 最长公共子序列(LCS)、最长递增子序列(LIS)、最长递增公共子序列(LICS)
- 最长递增子序列 lcs
- 动态规划——最长公共子序列(LCS)&最长递增子序列(LIS)
- LeetCode-Distinct Subsequences-唯一子序列-LCS变种DP
- 最长递增子序列问题的求解
- 关于最长递增子序列的3种解法
- 动态规划(DP),最长递增子序列(LIS)
- 公共子序列(lcs)
- 最长递增子序列
- HDU 1950 Bridging signals (最长递增子序列(nlogn算法)
- 动态规划 LCS 求两个序列A,B中所有的最长公共子序列
- 求数组中的最长递增子序列(编程之美2.16)
- 关于最长递增子序列问题的求解(LIS)
- hdu5256 序列变换 最长递增子序列
- CCNU ACM 2016夏季集训·最长递增子序列(LIS)
- 最长递增子序列(LIS)
- 最长递增子序列O(NlogN)算法