跳到正文

题解

题解 P3286 【[SCOI2014]方伯伯的商场之旅】

hzoi_liuchang约 3 分钟
原文
文章信息与版本

文章信息

发布
2021年1月20日
收录
2026年7月22日
更新
2026年11月18日
篇幅
约 3 分钟
获赞
2
题目
P3286

版本

  1. v1当前

分析

对于一堆石子来说,显然合并到石子位置的中位数是最优的

但是题中给出的石子达到了 101510^{15} ,暴力枚举显然是不现实的

但是把所有的石子都合并到同一个位置的贡献是可以计算的

所以我们考虑先把所有的石子合并到编号为 11 的一堆

然后再把石子从左往右移,每次算出减小的贡献减去

如果当前的位置在修改的位置左边,那么减小的贡献减去当前的数字

否则减小的贡献加上当前的数字

因为递归时从编号较大的石子递归到编号较小的石子

所以减小的贡献一定是先增大后减小的

因此为了防止数组越界,当当前值小于 00 时,直接 return0return 0

代码

C++
#include<cstdio>
#include<cstring>
#define ll long long
#define rg register
const int maxk=65,maxm=1e4+5;
ll f[maxk][maxm],l,r;
int num[maxk],cnt,k;
ll dfs(ll ws,ll tot,bool lim){
	if(!ws) return tot;
	if(!lim && f[ws][tot]!=-1) return f[ws][tot];
	int up=lim?num[ws]:(k-1);
	long long ans=0;
	for(int i=0;i<=up;i++){
		ans+=dfs(ws-1,tot+i*(ws-1),lim && i==up);
	}
	if(!lim) f[ws][tot]=ans;
	return ans;
}
ll dfs2(ll ws,ll tot,int xg,bool lim){
	if(tot<0) return 0;
	if(!ws) return tot;
	if(!lim && f[ws][tot]!=-1) return f[ws][tot];
	int up=lim?num[ws]:(k-1);
	long long ans=0;
	for(int i=0;i<=up;i++){
		ans+=dfs2(ws-1,tot+(ws<xg?-i:i),xg,lim && i==up);
	}
	if(!lim) f[ws][tot]=ans;
	return ans;
}
ll solve(ll now){
	cnt=0;
	while(now){
		num[++cnt]=now%k;
		now/=k;
	}
	memset(f,-1,sizeof(f));
	long long nans=dfs(cnt,0,1);
	for(int i=2;i<=cnt;i++){
		memset(f,-1,sizeof(f));
		nans-=dfs2(cnt,0,i,1);
	}
	return nans;
}
int main(){
	scanf("%lld%lld%d",&l,&r,&k);
	printf("%lld\n",solve(r)-solve(l-1));
	return 0;
}
原文