Codeforces 834D The Bakery (线段树+DP)

题目链接:http://codeforces.com/problemset/problem/834/D

#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define read(x,y) scanf("%d%d",&x,&y)
#define ll long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
const int  maxn =1e5+5;
const int mod=1e9+7;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
/*
我这是二刷,详情分析参考一刷:https://blog.csdn.net/qq_37451344/article/details/82526267
*/
int n,k;
int a[maxn];
int pre[maxn],show[maxn];///数据数组前驱数组
int dp[maxn];
int st[maxn<<2],lazy[maxn<<2];
void pushup(lrt){st[rt]=max(st[rt<<1],st[rt<<1|1]);}
void pushdown(lrt)
{
    if(lazy[rt])
    {
        st[rt<<1]+=lazy[rt];
        st[rt<<1|1]+=lazy[rt];
        lazy[rt<<1]+=lazy[rt];
        lazy[rt<<1|1]+=lazy[rt];
        lazy[rt]=0;
    }
}
void build(lrt)
{
    lazy[rt]=0;
    if(l==r) {st[rt]=dp[l];return ;}
    int mid=l+r>>1;
    build(lson),build(rson),pushup(root);
}
void update(lrt,int L,int R,int d)
{
    if(L<=l&&r<=R) {st[rt]+=d,lazy[rt]+=d;return ;}
    int mid=l+r>>1;
    pushdown(root);
    if(L<=mid) update(lson,L,R,d);
    if(mid<R) update(rson,L,R,d);
    pushup(root);
}
int query(lrt,int L,int R)
{
    if(L<=l&&r<=R) return st[rt];
    int mid=l+r>>1,ans=0;
    pushdown(root);
    if(L<=mid) ans=max(ans,query(lson,L,R));
    if(mid<R) ans=max(ans,query(rson,L,R));
    return ans;
}

int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        pre[i]=show[a[i]];
        show[a[i]]=i;
    }
    for(int i=1;i<=k;i++)
    {
        build(0,n,1);
        for(int j=1;j<=n;j++)
        {
            update(0,n,1,pre[j],j-1,1);///更新数组
            dp[j]=query(0,n,1,0,j-1);
        }
    }
    printf("%d\n",dp[n]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/82895363