码迷,mamicode.com
首页 > 其他好文 > 详细

【一维偏序】【最长上升子序列】【最长非降子序列】

时间:2019-08-15 05:51:02      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:str   pos   name   printf   code   names   bit   位置   nlogn   

两种方法,都是nlogn

树状数组型

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100003,M=50003;
int d[N];//原数组
int f[M];
int n,big;

int lowbit(int x)
{ return x&(-x); }
//用于求上升序列 
int ask(int x)//返回最后一个 小于等于x 的数的位置 
{
    int pos=0;
    while(x)
        pos=max(pos,f[x]),x-=lowbit(x);
    return pos;
}
void add(int x,int pos)
{
    while(x<=big)
        f[x]=max(f[x],pos),x+=lowbit(x);
}

int main()
{
    while(~scanf("%d",&d[++n])) big=max(big,d[n]);
    n--;
    int ans=1;
    for(int i=n;i;i--)
    {
        int ps=ask(d[i])+1; 
        ans=max(ans,ps);
        add(d[i],ps);//这是非降,就是插入在自己位置
    }//查的时候兄弟也查
    printf("%d\n",ans);
    
    ans=1;
    memset(f,0,sizeof(f));
    for(int i=1;i<=n;i++)
    {
        int ps=ask(d[i])+1; 
        ans=max(ans,ps);
        add(d[i]+1,ps);//这是上升
    }//查的时候不查兄弟
    printf("%d\n",ans);
    return 0;
} 

 

 

二分型

#include<cstdio>
#include<cstdlib> #include<algorithm> using namespace std; const int N=100003,M=50003; int n,f[N],d[N]; int main() { while(~scanf("%d",&d[++n])); n--; int ans=0; for(int i=n;i;i--)//这是非降 { int pos=upper_bound(f+1,f+ans+1,d[i])-f; ans=max(ans,pos); f[pos]=d[i]; } printf("%d\n",ans); ans=0,f[1]=0; for(int i=1;i<=n;i++)//这是上升 { int pos=lower_bound(f+1,f+ans+1,d[i])-f; ans=max(ans,pos); f[pos]=d[i]; } printf("%d\n",ans); return 0; }

【一维偏序】【最长上升子序列】【最长非降子序列】

标签:str   pos   name   printf   code   names   bit   位置   nlogn   

原文地址:https://www.cnblogs.com/xwww666666/p/11355669.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!