Codeforces1399-Codeforces Round #661 (Div. 3)-E1. Weights Division (easy version)

题目链接
题意:给定以1为根节点的树,定义树的总价值为从根节点到每个叶子结点的路径总和(注意一条路径可能会计算多次),可以选择任意边权减少一半向下取整,问最少的操作次数使得总价值小于等于S。

思路:dfs处理出每条边可以经过叶子结点的个数,优先队列来贪心使得操作数最少。比赛的时候没想太多,直接将边权乘经过次数塞进优先队列,一直wa,看了题解才恍然大悟,如果用边权乘叶子结点个数直接除二可能将答案变大,因为如果边权是奇数向下取整再乘叶子结点个数肯定比先乘后除减少的价值多。

AC代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define pb push_back
#define POP pop_back()
#define ll long long
#define db double
#define POP pop_back()
#define endl '\n'
#define cao cout << "DEBUG\n";
const int maxn = 1e5+5;
const int inf = 0x3f3f3f3f;
const ll inF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9+7;
const db eps = 1e-8;
struct node{
	int to;
	ll w;
};
vector<node>ve[maxn];
struct va{
	ll cnt , v;
	bool operator < (const va &b)const{
		return (v-v/2)*cnt < (b.v-b.v/2)*b.cnt;//先除后乘
	}
};
va sum[maxn];
ll dfs(int x , int fa , ll val){
	int len = ve[x].size();
	int to;
	ll cnt = 0;
	if(len == 1)cnt = 1;
	ll w;
	for(int i = 0;i < len;i++){
		to = ve[x][i].to;
		w = ve[x][i].w;
		if(to == fa)continue;
		cnt += dfs(to , x , w);
	}
	sum[x].v = val;
	sum[x].cnt = cnt;//所到达叶子结点的个数
	return cnt;
}
int main(){
	int u , v , t , n;cin >> t;
	ll s , w;
	while(t--){
		scanf("%d%lld",&n,&s);
		for(int i = 1;i <= n;i++)ve[i].clear() , sum[i].v = sum[i].cnt = 0;
		for(int i = 1;i < n;i++){
			scanf("%d%d%lld",&u,&v,&w);
			ve[u].pb((node){v,w});
			ve[v].pb((node){u,w});
		}
		dfs(1,0,0);
		priority_queue<va>q;
		ll cnt = 0;
		for(int i = 2;i <= n;i++)q.push(sum[i]) , cnt += sum[i].v*sum[i].cnt;
		int ans = 0;
		va tmp;
		ll out;
		while(!q.empty()){
			if(cnt <= s)break;
			ans++;
			tmp = q.top();
			out = tmp.v-tmp.v/2;
			cnt -= out*tmp.cnt;
			tmp.v -= out;
			q.pop();
			if(tmp.v == 0)continue;
			q.push(tmp);
		}
		cout << ans << endl;
	}
	return 0;
}

你可能感兴趣的:(刷题记录,dfs,贪心算法,队列)