Codeforces Round#525(Div.2)Ehab and a component choosing problem CodeForces - 1088E

本文介绍了一种使用树形动态规划算法解决特定问题的方法。在一个包含n个节点的树状结构中,目标是选择k个联通块,使得这些联通块中所有点的权值总和与联通块数量的比值最大化,且在多解情况下,联通块的数量尽可能多。文章通过详细的代码示例展示了如何实现这一算法。

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

题意:

有一个拥有 n 个节点的树,你要选 k 个联通块出来,使得这 k 个联通块中所有点的权值总和 sum 与联通块个数 k  的比值最大,多解时应使联通块的数量尽可能地多

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>
#include<vector>
using namespace std;
typedef long long int ll;
const int maxn =3e5+7;
const int maxm=10000;
const int mod =1e9+7;
const int INF=0x3f3f3f3f;
const double eps=1e-8;

int n,a[maxn],cnt;
vector<int>edge[maxn];
ll maxx=-mod;
ll dfs(int u,int pre,bool flag)
{
	ll sum=a[u];
	for(int v:edge[u])
		if(v!=pre)sum+=max(0ll,dfs(v,u,flag));
	if(!flag)maxx=max(maxx,sum);
    else if(sum==maxx)cnt++,sum=0;
    return sum;
}

int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	for(int i=1;i<n;i++)
	{
		int u,v; scanf("%d%d",&u,&v);
		edge[u].push_back(v);
		edge[v].push_back(u);
	}
	dfs(1,1,false),dfs(1,1,true);
	printf("%lld %d\n",cnt*maxx,cnt);
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值