LIS

来源:互联网 发布:java基础类库 编辑:程序博客网 时间:2024/05/01 18:01

这个算法的具体操作如下(by RyanWang):

开一个栈,每次取栈顶元素top和读到的元素temp做比较,如果temp > top 则将temp入栈;如果temp < top则二分查找栈中的比temp大的第1个数,并用temp替换它。 最长序列长度即为栈的大小top。

这也是很好理解的,对于x和y,如果x < y且Stack[y] < Stack[x],用Stack[x]替换Stack[y],此时的最长序列长度没有改变但序列Q的''潜力''增大了。

举例:原序列为1,5,8,3,6,7

栈为1,5,8,此时读到3,用3替换5,得到1,3,8; 再读6,用6替换8,得到1,3,6;再读7,得到最终栈为1,3,6,7。最长递增子序列为长度4。

用该算法完成POJ2533的具体代码如下:

#include <iostream>#define SIZE 1001 using namespace std; int main(){    int i, j, n, top, temp;    int stack[SIZE];    cin >> n;     top = 0;    /* 第一个元素可能为0 */    stack[0] = -1;    for (i = 0; i < n; i++)    {        cin >> temp;        /* 比栈顶元素大数就入栈 */        if (temp > stack[top])        {            stack[++top] = temp;        }        else        {            int low = 1, high = top;            int mid;            /* 二分检索栈中比temp大的第一个数 */            while(low <= high)            {                mid = (low + high) / 2;                if (temp > stack[mid])                {                    low = mid + 1;                }                else                {                    high = mid - 1;                }            }            /* 用temp替换 */            stack[low] = temp;        }    }     /* 最长序列数就是栈的大小 */    cout << top << endl;     //system("pause");    return 0;}