CF1088E Ehab and a component choosing problem

XLV.CF1088E Ehab and a component choosing problem

思路1.\(n^2\)DP。

考虑设\(f[i][j][0/1]\)表示:

节点\(i\),子树分了\(j\)个集合,节点\(i\)是/否在某个集合内的最大值。

但是这样是没有前途的——你再怎么优化也优化不了,还是只能从题目本身的性质入手。

思路2.分析性质,\(O(n)\)解决。

发现,答案最大也不会超过最大的那个集合的和。

我们考虑把每个集合看成一个数。那么,题目就让我们从一堆数中选一些数,使得它们的平均值最大。只选最大的那一个数,则答案就是最大的那一个数;但是最大的数可能不止一个,因此要找到所有值最大且互不相交的集合的数量。

找到最大的那个集合,可以直接\(O(n)\)DP出来。设\(f_x\)表示以\(x\)为根的子树中,包含\(x\)的所有集合中最大的那个,则有

\(f_x=\sum\limits_{y\in son_x}\max(f_y,0)\)

这样最大的那个集合就是\(f_x\)的最大值。

至于互不重叠的限制吗……再DP一遍,当一个\(f_x\)达到最大时,计数器++,并将\(f_x\)清零。

代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,val[300100],f[300100],mx=0x8080808080808080,res,head[300100],cnt;
bool vis[300100];
struct node{
	int to,next;
}edge[600100];
void ae(int u,int v){
	edge[cnt].next=head[u],edge[cnt].to=v,head[u]=cnt++;
	edge[cnt].next=head[v],edge[cnt].to=u,head[v]=cnt++;
}
void dfs1(int x,int fa){
	f[x]=val[x];
	for(int i=head[x];i!=-1;i=edge[i].next)if(edge[i].to!=fa)dfs1(edge[i].to,x),f[x]+=max(0ll,f[edge[i].to]);
}
void dfs2(int x,int fa){
	f[x]=val[x];
	for(int i=head[x];i!=-1;i=edge[i].next)if(edge[i].to!=fa)dfs2(edge[i].to,x),f[x]+=max(0ll,f[edge[i].to]);
	if(f[x]==mx)res++,f[x]=0x8080808080808080;
}
signed main(){
	scanf("%lld",&n),memset(head,-1,sizeof(head));
	for(int i=1;i<=n;i++)scanf("%lld",&val[i]);
	for(int i=1,x,y;i<n;i++)scanf("%lld%lld",&x,&y),ae(x,y);
	dfs1(1,0);
	for(int i=1;i<=n;i++)mx=max(mx,f[i]);
	dfs2(1,0);
	printf("%lld %lld\n",1ll*res*mx,res);
	return 0;
}

原文地址:https://www.cnblogs.com/Troverld/p/14597286.html