解析:设dp[i]为考虑前i棵树的最小收益。
那么dp[i] = min(dp[j]+max(h[j+1...i]));
显然不能直接状态转移,但是又想不出logn的做法,于是就套上了块状数组。
[code]:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
using namespace std;
typedef long long LL;
const int maxn = 2e5+5;
const LL INF = 1e15;
const int N = 1050;
inline bool read(int &ret){
char c;int sgn;
if(c = getchar(),c==EOF) return 0;
while(c != '-'&&(c<'0'||c>'9')) c=getchar();
sgn = (c=='-')?-1:1;
ret = (c=='-')?0:(c-'0');
while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
ret*=sgn;
return 1;
}
LL dp[maxn],f[N];
int n,a[maxn],b[maxn],c[maxn];
int sqr,num,h[N],L[N],R[N],mark[N];
//h[i]为第i个块的最大树高度
//f[i]为第i个块内的最优解
void build(){
int i,j;
sqr = (int)ceil(sqrt(1.0*n));
num = (n-1)/sqr+1;
memset(dp,63,n*sizeof(LL));
for(i = 0;i < num;i++){
L[i] = i*sqr;
R[i] = min(n,(i+1)*sqr);
mark[i] = -1;
}
}
void push_down(int id){
if(mark[id]==-1) return;
int i,j;
for(i = L[id];i < R[id];i++){
b[i] = mark[id];
}
mark[id] = -1;
}
void update(int p,int x){
int i,j,id = p/sqr;
push_down(id);
f[id] = INF;
h[id] = 0;
for(i = p;i >= L[id];i--){
b[i] = max(b[i],x);
f[id] = min(f[id],b[i]+(i?dp[i-1]:0));
h[id] = max(h[id],b[i]);
}
for(i = id-1;i >= 0;i--){
if(h[i] <= x){
mark[i] = x;
h[i] = x;
f[i] = x + (L[i]?dp[L[i]-1]:0);
}else{
push_down(i);
f[i] = INF;
for(j = L[i];j < R[i];j++){
b[j] = max(b[j],x);
f[i] = min(f[i],b[j]+(j?dp[j-1]:0));
}
break;
}
}
}
LL query(int l,int r){
int li,ri,i,j;
LL ans = INF;
li = l/sqr,ri = r/sqr;
push_down(li);push_down(ri);
if(li==ri){
for(i = l;i <= r;i++){
ans = min(ans,b[i]+(i?dp[i-1]:0));
}
}else{
for(i = l;i < R[li];i++){
ans = min(ans,b[i]+(i?dp[i-1]:0));
}
for(i = L[ri];i <= r;i++){
ans = min(ans,b[i]+(i?dp[i-1]:0));
}
}
for(i = li+1;i <= ri-1;i++) ans = min(ans,f[i]);
return ans;
}
void sol(){
int i,j;
build();
for(i = 0;i < n;i++) c[a[i]] = -1;
for(i = 0,j = 0;i < n;i++){
j = max(j,c[a[i]]+1);
c[a[i]] = i;
update(i,b[i]);
dp[i] = query(j,i);
}
printf("%lld\n",dp[n-1]);
}
int main(){
int i,j,cas;
read(cas);
for(int T=1;T<=cas;T++){
read(n);
for(i = 0;i < n;i++){
read(a[i]);read(b[i]);
}
printf("Case %d: ",T);
sol();
}
return 0;
}