题解 CF833B 【The Bakery】
这道题很好列出状态转移方程,dp[i][j]=max{dp[k][j-1]+cnt[k+1][i]}
dp[i][j]意为1~i之间分割j次所产生的最大值。cnt[i][j]表示i-j之间不同的颜色个数。
看到max可以考虑线段树优化,也就是如果我们有办法在O(logn)的时间内计算出cnt[i][j]的值就可以了,考虑一种颜色能够产生贡献的范围,为他上一次出现的位置到他当前的位置,产生贡献为1,可以使用线段树区间加,给pre[i]~i都加上1,从1到n进行枚举,逐渐进行上面的操作,每次换下一层的时候重构线段树,这样计算cnt[i][j]的复杂度就变成了logn的 orz
总复杂度是O(nklogn),时限2500ms完全不虚~
代码如下
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define lson root<<1
#define rson root<<1|1
using namespace std;
struct node
{
int l,r,sum,lazy;
}tr[140010];
int dp[60][40000],pre[35010],pos[35010];
void init()
{
memset(tr,0,sizeof(tr));
}
void push_up(int root)
{
tr[root].sum=max(tr[lson].sum,tr[rson].sum);
}
void push_down(int root)
{
tr[lson].sum+=tr[root].lazy;
tr[lson].lazy+=tr[root].lazy;
tr[rson].sum+=tr[root].lazy;
tr[rson].lazy+=tr[root].lazy;
tr[root].lazy=0;
}
void build(int root,int l,int r,int now)
{
if(l==r)
{
tr[root].l=l;
tr[root].r=r;
tr[root].sum=dp[now][l-1];
return ;
}
tr[root].l=l;
tr[root].r=r;
int mid=(l+r)>>1;
build(lson,l,mid,now);
build(rson,mid+1,r,now);
push_up(root);
}
void update(int root,int l,int r,int val)
{
if(tr[root].l==l&&tr[root].r==r)
{
tr[root].sum+=val;
tr[root].lazy+=val;
return ;
}
if(tr[root].lazy)
{
push_down(root);
}
int mid=(tr[root].l+tr[root].r)>>1;
if(mid<l)
{
update(rson,l,r,val);
}
else
{
if(mid>=r)
{
update(lson,l,r,val);
}
else
{
update(lson,l,mid,val);
update(rson,mid+1,r,val);
}
}
push_up(root);
}
int query(int root,int l,int r)
{
if(tr[root].l==l&&tr[root].r==r)
{
return tr[root].sum;
}
if(tr[root].lazy)
{
push_down(root);
}
int mid=(tr[root].l+tr[root].r)>>1;
if(mid<l)
{
return query(rson,l,r);
}
else
{
if(mid>=r)
{
return query(lson,l,r);
}
else
{
return max(query(lson,l,mid),query(rson,mid+1,r));
}
}
}
int main()
{
int n,k,t;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%d",&t);
pre[i]=pos[t]+1;
pos[t]=i;
}
for(int i=1;i<=k;i++)
{
init();
build(1,1,n,i-1);
for(int j=1;j<=n;j++)
{
update(1,pre[j],j,1);
dp[i][j]=query(1,1,j);
}
}
printf("%d\n",dp[k][n]);
}