算法 - 求一个数组的最长递减子序列(C++)
来源:互联网 发布:稀疏矩阵的压缩方法 编辑:程序博客网 时间:2024/06/08 18:55
//****************************************************************************************************//// 求一个数组的最长递减子序列 - C++ - by Chimomo//// 题目: 求一个数组的最长递减子序列,比如{8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1}的最长递减子序列为{14,8,3,2,1}。//// Answer: Scan from left to right, maintain a decreasing sequence. For each number, binary search in the decreasing sequence to see whether it can be substituted.////****************************************************************************************************#include <iostream>#include <cassert>#include <stack>using namespace std ;int BinarySearch(int *A, int nTarget, int nLen);// Find the longest decreasing sequence in array A of length nLen.void FindLongestDecreasingSequence(int *A, int nLen){int *index = new int[nLen];int *LDS = new int[nLen];index[0] = A[0];LDS[0] = 1;int indexLen = 1;for (int i = 1; i < nLen; i++){int pos = BinarySearch(index, A[i], indexLen);index[pos] = A[i];LDS[i] = pos + 1;if(pos >= indexLen){indexLen++;}}int ResultLen = indexLen;for (int i = nLen; i >= 0; i--){if(LDS[i] == ResultLen){index[ResultLen - 1] = A[i];ResultLen--;}}for (int i = 0; i < indexLen; i++){cout << index[i] << " ";}delete [] index;}// Binary search nTarget in array A of length nLen.int BinarySearch(int *A, int nTarget, int nLen){assert(A != NULL && nLen > 0);int start = 0;int end = nLen - 1;while (start <= end){int mid = (start + end) / 2;if(nTarget > A[mid]){end=mid-1;}else if(nTarget<A[mid]){start=mid+1;}else{return mid;}}return start;}int main(){int A[] = {8, 14, 6, 2, 8, 14, 3, 2, 7, 4, 7, 2, 8, 101, 23, 6, 1, 2, 1, 1};int nLen = sizeof(A) / sizeof(int);FindLongestDecreasingSequence(A, nLen);return 0;}// Output:/*14 8 7 6 2 1*/
706 0
- 算法 - 求一个数组的最长递减子序列(C++)
- 数据结构——算法之(025)( 求一个数组的最长递减子序列)
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列
- 求数组的最长递减子序列
- 求数组的最长递减子序列 (dp)
- 求一个整数数组最长递减子序列
- coding - 求数组的最长递减子序列
- 计蒜客-求数组的最长递减子序列
- 47.创新工场: 求一个数组的最长递减子序列
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
- 求一个数组的最长递减子序列比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5, 4,3,2}
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}
- 求一个数组的最长递减子序列 比如{9,4,3,2,5,4,3,2}的最长递减子序列为{9,5,4,3,2}。
- Ztree 异步加载 的初步研究
- 习近平 李克强就韩国客轮沉没事故向韩方致慰问电
- unicode码 java中文
- iOS开发之八:UISlider、UISegmentedControl、UIPageControl的使用
- 黑马程序员-OC中字符串的操作-NSString+NSMutableString+NSValue+NSAraay用法汇总
- 算法 - 求一个数组的最长递减子序列(C++)
- 文件I/O(1)
- 当Windows 7或者Windows2008加入域后,登陆时出现“服务器上的安全数据库没有此工作站信任关系的计算机帐户”,导致无法登陆到域
- 用netinstall安装RouterOS教程
- NC(Net cat ) 使用详解(用作文件传输,端口转发,反弹Shell)
- resin3使用的一些体会
- Host 'ETCV3' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'
- c++程序移植到android上问题记录
- spring3.x读取文件报错