2018.10.19 bzoj1584: Cleaning Up 打扫卫生(线性dp)

这是一道关于动态规划(DP)的妙题,通过分析发现,每段不同数的个数不超过sqrt(n),可以利用pos数组记录特定数量不同数的位置进行转移,从而实现O(n * sqrt(n))的时间复杂度解题。给出的代码实现了这一思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门
dp妙题。


考虑到每个位置分一组才花费 n n n的贡献。
因此某一段不同的数的个数不能超过 s q r t ( n ) sqrt(n) sqrt(n),于是对于当前的位置 i i i我们记 p o s [ j ] pos[j] pos[j]表示 p o s [ j ] + 1 pos[j]+1 pos[j]+1 i i i恰好有 j j j个不同的数。
这样 f [ i ] f[i] f[i]就可以从 p o s [ j ] pos[j] pos[j]转移过来。
由于 p o s pos pos数组最多 s q r t ( n ) sqrt(n) sqrt(n)个因此时间复杂度 O ( n ∗ s q r t ( n ) ) O(n*sqrt(n)) O(nsqrt(n))
代码:

#include<bits/stdc++.h>
#define N 40005
using namespace std;
inline int read(){
	int ans=0;
	char ch=getchar();
	while(!isdigit(ch))ch=getchar();
	while(isdigit(ch))ans=(ans<<3)+(ans<<1)+(ch^48),ch=getchar();
	return ans;
}
int n,m,a[N],f[N],las[N],pos[N],cnt[N],tot=0;
int main(){
	n=read(),m=read();
	memset(cnt,0,sizeof(cnt));
	for(int i=1;i<=n;++i){
		int x=read();
		if(x!=a[tot])a[++tot]=x;
	}
	n=tot,m=sqrt(n),f[0]=0;
	for(int i=1;i<=n;++i){
		f[i]=0x3f3f3f3f;
		for(int j=1;j<=m;++j)if(las[a[i]]<=pos[j])++cnt[j];
		las[a[i]]=i;
		for(int j=1;j<=m;++j){
			if(cnt[j]>j){
				int tmp=pos[j]+1;
				while(las[a[tmp]]>tmp)++tmp;
				pos[j]=tmp,--cnt[j];
			}
			f[i]=min(f[i],f[pos[j]]+j*j);
		}
	}	
	cout<<f[n];
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值