Codeforces Round #661 (Div. 3) E1 - Weights Division (easy version) --贪心,优先队列,树

题目描述
在这里插入图片描述
题意
给你一棵树,每条边都有权值,求 sum:叶子节点到其他所有节点的路径和
再给你一种操作: 使 任意一条边的权值减半,求最少的操作数使得 sum<=k (k给出)

思路
1 . 如何求sum
可以算出每条边被使用的次数leaf ,然后sum+=a[i].w*leaf ,算出每条边的贡献
2.怎样使得操作数目最少
要使得sum 变得小于等于k ,还要操作次数最少,可以先贡献大的边开始改变,这样会使sum 更接近k
一条边的贡献 (a[i].w-a[i].w/2)*leaf

Code

struct edge {
	ll u,v,w,next;
} a[maxn];
struct node {
	ll val,leaf;
	friend	bool operator < (node x, node y) {
		return (x.val-x.val/2)*x.leaf<(y.val-y.val/2)*y.leaf;
	}
};
ll n,k,head[maxn],cnt,sum,ans;
void add(ll u,ll v,ll w) {
	a[cnt].u=u;
	a[cnt].v=v;
	a[cnt].w=w;
	a[cnt].next=head[u];
	head[u]=cnt++;
}
priority_queue<node>q;
ll  dfs(ll u,ll p) {
	ll le=0;
	for(int i=head[u]; ~i; i=a[i].next) {
		ll v=a[i].v;
		if(v==p) continue;
		ll temp=dfs(v,u);
		q.push({a[i].w,temp});
		sum+=a[i].w*temp;
		le+=temp;
	}
	return le?le:1;
}
int main() {
	int toto=read();
	while(toto--) {
		n=read(),k=read();
		sum=ans=cnt=0;
		while(q.size()) q.pop();
		mst(head,-1);
		for(int i=1 ; i<n ; i++) {
			ll u=read();
			ll v=read();
			ll w=read();
			add(u,v,w);
			add(v,u,w);
		}
		dfs(1,0);
		while(sum>k) {
			ans++;
			node fr=q.top();
			q.pop();
			sum-=(fr.val-fr.val/2)*fr.leaf;
			node temp;
			temp.val=fr.val/2;
			temp.leaf=fr.leaf;
			q.push(temp);
		}
		cout<<ans<<endl;
	}
	return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值