跳到正文

个人记录

最长上升子序列(基础dp)

hkr04约 2 分钟
原文
文章信息与版本

文章信息

发布
2018年8月24日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

题目地址 代码前说明:a是存数的数组,f[i]表示长度为i的上升子序列中最后(即最大的数) 另:手写二分查找可以跑得更快

C++
#include <cstdio>
#include <iostream>
#include <algorithm>
const int INF=0x3f3f3f3f;
using namespace std;
int main()
{
    int n,a[1010],f[1010];
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        f[i]=INF;//初始化全为最大
    }
    f[1]=a[1];//一开始长度为1的上升子序列中只有数组中第一个数
    int ans=1;//初始化ans(至少会有长度为1的嘛……)
    for (int i=1;i<=n;i++)
    {
        if (a[i]>f[ans])f[++ans]=a[i];
        //如果当前的数大于当前最长上升子序列的最大一个数时,序列长度++,将这个数存入
        else
        {
            int pos=lower_bound(f+1,f+1+n,a[i])-f;//找到第一个以大于等于a[i]的数结尾的子序列,将它的结尾改为a[i](保证答案最优)(易证答案数组具有单调性)
            f[pos]=a[i];
        }
    }
    printf("%d\n",ans);
    return 0;
}
原文