poj 2533 最长上升子序列

本文介绍了一种使用C++实现动态数组的方法,并通过二分查找优化了查找操作的效率。同时,利用algorithm库中的lower_bound函数简化了查找过程,提高了程序的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;       //这个下标的前一个数即为小于temp的最大的数
        }
    }
 
    /* 最长序列数就是栈的大小 */
    cout << top << endl;
 
    //system("pause");
    return 0;
}  

 
 
用algorithm里的lower_bound函数找下界实现:#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <vector>
#include <cstdlib>

using namespace std;

int main()
{
    int stack[1005];
    int n,top=0,temp;
    cin>>n;
    stack[0]=-1;
    for(int i=0;i<n;i++)
    {
        cin>>temp;
        if(temp>stack[top])
        stack[++top]=temp;
        else
        {
            int loc=lower_bound(stack,stack+top,temp)-stack;  //返回第一个>=temp的数的下标,则这个数的前一个数就是<temp的下标最大的数
              stack[loc]=temp;
        }
    }
    cout<<top<<endl;
    return 0;
}





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值