ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

AT4995-[AGC034E] Complete Compress【树形dp】

2021-02-12 13:30:34  阅读:222  来源: 互联网

标签:rt Complete AT4995 int AGC034E ans mx dp dis


正题

题目链接:https://www.luogu.com.cn/problem/AT4995


题目大意

n n n个点的一棵树,上面有一些棋子,每次可以选择两个棋子移动到他们之间的路径上相邻的点上,求最少多少步能移动到一个点上。

n ∈ [ 1 , 2000 ] n\in[1,2000] n∈[1,2000]


解题思路

如果固定最终节点的话,这个节点 r t rt rt可行的话那么答案一定是 ∑ d i s ( r t , x ) 2 \frac{\sum dis(rt,x)}{2} 2∑dis(rt,x)​。

那么现在就转变为一个判定性问题,我们现在的操作变为了每次选择两个没有祖先关系的点,然后将它们往它们的 L C A LCA LCA处移动一格。

同样的,我们发现如果我们在处理一个点 x x x作为 L C A LCA LCA时,我只会关心所有节点来自它的哪个儿子而不用考虑具体的位置。所以可以搞树形 d p dp dp。

设 f x f_x fx​表示 x x x的子树内最多的移动次数,定义 s x = ∑ y ∈ s u b t r e e ( x ) d i s ( x , y ) s_x=\sum_{y\in subtree(x)}dis(x,y) sx​=∑y∈subtree(x)​dis(x,y)的话,那么我们的转移和 m a x { s y } ( x − > y ) max\{s_y\}(x->y) max{sy​}(x−>y)有关。

若 m a x { s y } × 2 ≤ s x max\{s_y\}\times 2\leq s_x max{sy​}×2≤sx​,那么这里面的节点可以两两配对, f x = s x 2 f_x=\frac{s_x}{2} fx​=2sx​​。

否则他 s s s最大的子树 y y y之中会有剩余的节点无法相互匹配,那么有 f x = s x − s y + m i n { f y , s y − ⌊ s x 2 ⌋ } f_x=s_x-s_y+min\{f_y,s_y-\lfloor\frac{s_x}{2}\rfloor\} fx​=sx​−sy​+min{fy​,sy​−⌊2sx​​⌋}

然后如果 f x = s x 2 f_x=\frac{s_x}{2} fx​=2sx​​那么 x x x就是可行的答案

时间复杂度 O ( n 2 ) O(n^2) O(n2)


code

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=2100;
struct node{
	int to,next;
}a[N<<1];
int n,tot,ls[N],s[N],w[N],f[N],ans;
char v[N];
void addl(int x,int y){
	a[++tot].to=y;
	a[tot].next=ls[x];
	ls[x]=tot;return;
}
void dp(int x,int fa){
	s[x]=w[x]=0;
	int mx=0,son=0;
	for(int i=ls[x];i;i=a[i].next){
		int y=a[i].to;
		if(y==fa)continue;
		dp(y,x);w[x]+=w[y];
		s[x]+=s[y]+w[y];
		if(s[y]+w[y]>mx)
			mx=s[y]+w[y],son=y;
	}
	if(mx*2>s[x])
		f[x]=s[x]-mx+min(f[son],mx-s[x]/2);
	else f[x]=s[x]/2;
	w[x]+=(v[x]=='1');
	return;
}
int main()
{
	scanf("%d",&n);
	scanf("%s",v+1);
	for(int i=1;i<n;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		addl(x,y);addl(y,x);
	}
	ans=1e9;
	for(int i=1;i<=n;i++){
		dp(i,i);
		if(s[i]&1)continue;
		if(f[i]==s[i]/2)
			ans=min(ans,f[i]);
	}
	if(ans==1e9)puts("-1");
	else printf("%d\n",ans);
	return 0;
}

标签:rt,Complete,AT4995,int,AGC034E,ans,mx,dp,dis
来源: https://blog.csdn.net/Mr_wuyongcong/article/details/113794481

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有