题解:CF1399E1 Weights Division (easy version)
CF1399E1 Weights Division (easy version) 题解
看到有的题解把这道题的贪心分解的比较细致,看上去比较复杂。其实这道题的思路非常的直接。 题意不过多赘述,首先要对树有一个大概的了解。树上是无环的,所以根据这个性质,我们只要确定根节点,是可以对于树有一个关于点深度方面的明确的定义的(从根节点经过几条边的简单路径可以到达该节点,根节点深度为 0)。以及一棵树中,每个父节点有儿子节点,没有儿子节点的是叶子节点。
根据树的特殊的性质,结合这道题可知,从根节点走向所有的叶子节点的路径总权值之和就是每条边的权值 × 该边被多少条“根-叶子”路径覆盖的总和(简单的
举个简单的例子。若边
其中
贪心操作
题目要求通过“将边权除以二(向下取整)”的操作,让
所以这里的贪心策略直接按照删除边之后减少的边权乘以出现次数,得到对于这条边进行操作之后对于总数 priority_queue 每次取出队首做一遍操作即可。
对于这道题:
对于边
- 第一次操作后,边权变为
\lfloor \frac{w}{2} \rfloor ,总权值和减少的量:gain = (w - \lfloor \frac{w}{2} \rfloor) \times cnt_e - 第二次操作后,边权变为
\lfloor \frac{w}{4} \rfloor ,单次收益变为:gain' = (\lfloor \frac{w}{2} \rfloor - \lfloor \frac{w}{4} \rfloor) \times cnt_e 以此类推,每次对同一条边操作的收益会严格递减。
这意味着:对同一条边的多次操作,收益是“先大后小”的;而不同边之间,我们只需每次选当前收益最大的操作执行,就能保证总操作次数最少。
具体实现
通过一次 DFS 或 BFS 遍历树即可完成。需要注意的是本题不保证按照父到子的顺序输入边,所以必须建双向边并在函数中判父节点跑,边数组开两倍。
priority_queue 默认大根堆。但是我的代码实现传了三个参,所以用了结构体并重载了 < 运算符(太菜)
AC Code
#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
// typedef long long ll;
#define int long long
#define mp(a, b) make_pair(a, b)
const int N = 1e5 + 10;
int e[N << 1], ne[N << 1], h[N], w[N << 1], idx;
int tot = 0;
void add(int u, int v, int w1){
e[idx] = v, ne[idx] = h[u], w[idx] = w1, h[u] = idx++;
}
int n, S;
int dp[N];
struct node{
int times, w1, score;
bool operator <(const node &W)const{
return score < W.score;
}
};
priority_queue<node> heap;
void dfs(int u, int fa){
bool flag = 0;
for(int i=h[u];~i;i=ne[i]){
int j = e[i];
if(j == fa) continue;
flag = 1;
dfs(j, u);
tot += w[i] * dp[j];//计算加入总边权
heap.push({dp[j], w[i], (w[i] - w[i] / 2) * dp[j]});
dp[u] += dp[j];
}
if(!flag){
dp[u] = 1;
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int T;
cin >> T;
while(T --){
memset(h, -1, sizeof h);
memset(dp, 0, sizeof dp);
idx = 0;
while(!heap.empty()) heap.pop();
tot = 0;
cin >> n >> S;
for(int i=1;i<n;i++){
int u, v, w;
cin >> u >> v >> w;
add(u, v, w);
add(v, u, w);
}
dfs(1, -1);
int ans = 0;
while(tot > S){
ans ++;
auto t = heap.top();
heap.pop();
int times = t.times, w1 = t.w1, score = t.score;
tot -= t.score;
int w1_ = w1 / 2;
heap.push({times, w1_, (w1_ - w1_ / 2) * times});
}
cout << ans << "\n";
}
return 0;
}