跳到正文

题解

题解:P9128 [USACO23FEB] Fertilizing Pastures G

Tokisaki__kurumi约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年10月29日
收录
2026年4月29日
更新
2026年11月16日
篇幅
约 4 分钟
题目
P9128

版本

  1. v1当前

P9128

思路:邻项交换,树上 dp。先考虑第一问,很显然就是 dfs 一遍,T=0T=0 时答案是 2×(n−1)2\times (n-1),T=1T=1 时答案是 2×(n−1)−depmax2 \times (n-1) -dep_{max}。接下来考虑第二问,直接枚举遍历顺序时间复杂度肯定爆炸,所以我们要找到一种遍历方式来达到最优。考虑邻项交换法,对于一对相同父亲相邻的节点,很显然交换他们两个是不会影响其他答案的。设这两个点为 x,yx,y,fxf_{x} 为以 xx 为根的子树的最小贡献,cc 为之前耽误的时间,sumxsum_{x} 表示以 xx 为根的子树的 aa 的和,什么时候不会交换,列出式子:

fx+(c+1)×sumx+fy+(c+1+2×szx)×sumy<fy+(c+1)×sumy+fx+(c+1+2×szy)×sumxf_{x}+(c+1)\times sum_{x}+f_{y}+(c+1+2 \times sz_{x})\times sum_y<f_{y}+(c+1)\times sum_{y}+f_{x}+(c+1+2 \times sz_{y})\times sum_x

化简得:

szx×sumy<szy×sumxsz_{x}\times sum_{y}<sz_{y}\times sum_{x}

所以我们得到了遍历顺序。那对于 T=1T=1 的情况,我们就是对于那些最深的子树,选择将其最后选的所有情况的最小值。对于他的式子也不难推就是:

gx=min⁡depmax⁡to=depmax⁡xfx−valto−2×szx×suf+gto+(2×szx−2×szto−1)×sumtog_{x}=\min_{dep \max _{to}=dep \max _{x}}f_{x}-val_{to}-2\times sz_{x}\times suf+g_{to}+(2\times sz_{x}-2\times sz_{to}-1)\times sum_{to}

然后这道题就做完了,时间复杂度 O(nlog⁡n)\mathcal{O}(n\log n)。

code

C++
int dep[N],maxdep[N];
int f[2][N],val[N],sum[N];
int n,type;
int a[N];
int sz[N];
vector<int> son[N];
inline bool cmp(int x,int y){
	return sz[x]*sum[y]<sz[y]*sum[x];
}
void dfs(int x){
	sz[x]=1;
	maxdep[x]=dep[x];
	sum[x]=a[x];
	for(auto to:son[x]){
		dep[to]=dep[x]+1;
		dfs(to);
		sum[x]+=sum[to];
		sz[x]+=sz[to];
		maxdep[x]=max(maxdep[x],maxdep[to]);
	}
	sort(son[x].begin(),son[x].end(),cmp);
	int c=1;
	for(auto to:son[x]){
		val[to]=f[1][to]+c*sum[to];
		f[1][x]+=val[to];
		c+=sz[to]*2;
	}
	int suf=0;
	f[0][x]=inf;
	for(int i=son[x].size()-1;i>=0;--i){
		int to=son[x][i];
		if(maxdep[to]!=maxdep[x]){
			suf+=sum[to];
			continue;
		}
		c=2*(sz[x]-sz[to]-1);
		f[0][x]=min(f[0][x],f[1][x]-val[to]-2*sz[to]*suf+f[0][to]+sum[to]*(c+1));
		suf+=sum[to];
	}
	if(f[0][x]==inf) f[0][x]=0;
}
inline void solve(){
	read(n,type);
	for(int i=2;i<=n;++i){
		int fa;
		read(fa,a[i]);
		son[fa].pb(i);
	}
	dfs(1);
	if(!type) write(2*(n-1),f[1][1]);
	else write(2*(n-1)-maxdep[1],f[0][1]);
}
原文