Dilworth定理通俗说法

不上升子序列的最小划分数等于最长上升子序列长度
不下降子序列的最小划分数等于最长下降子序列长度
如 1 2 3 4 3
求不下降在子序列最小划分数 即最长下降子序列 【4 3】的长度 2,分为【1 2 3 3】,【4】。
另外就是如需要求每个数分别划分到了那一组,也可同时统计。
例题牛客网

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include<set>
#include<cmath>
#include<string>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
const int maxn=100000+5;
int lx[maxn],ly[maxn]={0},w[maxn];
bool cmp(int x,int y)
{
    return lx[x]<lx[y];
}
int num[maxn]={0};
int st[maxn];
int  find(int x,int len)
{
    int  l=1,r=len;
    int ans,h;
    while(l<=r)
    {
        int mid=l+(r-l)/2;
        if(ly[st[mid]]<ly[x])
        {
            ans=st[mid];
            h=mid;
            r=mid-1;
        }
        else
        {
            l=mid+1;
        }   
    }
    st[h]=x;
    return ans;
}
int  main()
{
    int n;
    //freopen("tte.txt","r",stdin);
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d %d",&lx[i],&ly[i]);
        w[i]=i;
    }
    sort(w+1,w+n+1,cmp);
    int len=0;
    int cnt=1;
    st[++len]=w[1];
    num[w[1]]=1;
    for(int i=2;i<=n;i++)
    {
        int o=w[i];
        if(ly[o]<ly[st[len]])
        {
            st[++len]=o;
            num[o]=++cnt;
        }
        else
        {
            int wh=find(o,len);
            num[o]=num[wh];
        } 
    }
    printf("%d\n",len);
    for(int i=1;i<=n;i++)
    {
        if(i!=1) printf(" %d",num[i]);
        else printf("%d",num[i]);
    }
    return 0;
}
发布了23 篇原创文章 · 获赞 0 · 访问量 336

猜你喜欢

转载自blog.csdn.net/qq_45753808/article/details/104361984
今日推荐