最长上升子序列(LIS)

来源:互联网 发布:东方的漫画软件 编辑:程序博客网 时间:2024/06/04 19:24

参考博客:http://blog.csdn.net/shuangde800/article/details/7474903

循环从1到n,当添加一个新元素时,为了能得到更长的递增序列len+1,那么必须要保证已知的len的递增序列的尾元素最小,那么新元素才有机会加入构成len+1的序列,这一过程中直接用upper_bound(形成非严格递增)或lower_bound(形成严格递增)维护

附模板:

#include<cstdio>#include<algorithm>using namespace std;const int MAXN = 100000 + 5;int Ans[MAXN], gt[MAXN], tot;int main(){    int t;scanf("%d", &t);    while (t--)    {        tot = 0;        int n;scanf("%d", &n);        for (int i = 0;i < n;++i)            scanf("%d", gt + i);        Ans[tot++] = gt[0];        for (int i = 1;i < n;++i)        {            if (gt[i] >= Ans[tot-1]) Ans[tot++] = gt[i];            else            {                int pos = upper_bound(Ans, Ans + tot, gt[i]) - Ans;                Ans[pos] = gt[i];            }        }        for (int i = 0;i < tot;++i)            printf("%d ", Ans[i]);        puts("");    }    return 0;}
原创粉丝点击