CF 833 B. The Bakery

时间:2021-09-23 15:47:22

B. The Bakery

http://codeforces.com/contest/833/problem/B

题意:

  将一个长度为n的序列分成k份,每份的cost为不同的数的个数,求最大cost的和。1≤n≤35000,1≤k≤50

分析:

  dp[i][j]表示前i个数,分了j份。dp[i][k]=dp[j][k-1]+cost(j+1,i);cost(j+1,i)为这一段中不同数的个数。

  然后考虑如何优化。发现每次增加一个位置,pre[i]~i-1区间的每个转移的位置的cost+1。然后每次转移是在上一个dp数组中取最大值,于是线段树维护。

代码:

 /*
* @Author: mjt
* @Date: 2018-10-15 14:52:11
* @Last Modified by: mjt
* @Last Modified time: 2018-10-15 15:27:53
*/
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iostream>
#include<cctype>
#include<set>
#include<vector>
#include<queue>
#include<map>
#define fi(s) freopen(s,"r",stdin);
#define fo(s) freopen(s,"w",stdout);
using namespace std;
typedef long long LL; inline int read() {
int x=,f=;char ch=getchar();for(;!isdigit(ch);ch=getchar())if(ch=='-')f=-;
for(;isdigit(ch);ch=getchar())x=x*+ch-'';return x*f;
} const int N = ; int dp[N][], pre[N], last[N], a[N];
int n, k; #define Root 1, n, 1
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
struct SegmentTree {
int mx[N << ], tag[N << ], Cur;
inline void pushup(int rt) { mx[rt] = max(mx[rt << ], mx[rt << | ]); }
inline void pushdown(int rt) {
if (tag[rt]) {
tag[rt << ] += tag[rt]; mx[rt << ] += tag[rt];
tag[rt << | ] += tag[rt]; mx[rt << | ] += tag[rt];
tag[rt] = ;
}
}
void build(int l,int r,int rt) {
tag[rt] = ;
if (l == r) {
mx[rt] = dp[l][Cur]; return ;
}
int mid = (l + r) >> ;
build(lson); build(rson);
pushup(rt);
}
void update(int l,int r,int rt,int L,int R) {
if (L <= l && r <= R) {
mx[rt] ++; tag[rt] ++;
return ;
}
pushdown(rt);
int mid = (l + r) >> ;
if (L <= mid) update(lson, L, R);
if (R > mid) update(rson, L, R);
pushup(rt);
}
int query(int l,int r,int rt,int L,int R) {
if (L <= l && r <= R) {
return mx[rt];
}
pushdown(rt);
int mid = (l + r) >> , res = ;
if (L <= mid) res = max(res, query(lson, L, R));
if (R > mid) res = max(res, query(rson, L, R));
return res;
}
}T; void solve(int now) {
T.Cur = now - ; T.build(Root);
for (int i=now; i<=n; ++i) {
T.update(Root, pre[i], i - ); // 线段树维护的是dp[j][now-1]+cost(j+1,i)的值,所以pre[i]~i-1这个区间加1!!!
dp[i][now] = T.query(Root, , i - );
}
} int main() {
n = read(), k = read();
for (int cnt=,i=; i<=n; ++i) {
a[i] = read();
pre[i] = last[a[i]]; last[a[i]] = i;
if (pre[i] == ) cnt ++;
dp[i][] = cnt;
}
for (int i=; i<=k; ++i) solve(i);
cout << dp[n][k];
return ;
}