题目描述:
题意:
给你一棵树,每条边都有权值,求 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;
}