Codeforces E1. Weights Division (easy version) (树dfs & 边的利用次数)

传送门

题意: 给定一棵以 1 号点为根的带权有根树。每次可选择一条边将其边权除以2(下取整),试问至少经过多少次选择,才能使得所有根节点到叶子节点的路径权值和不超过S?
在这里插入图片描述
思路:

  • 利用有限队列每次选择权值最大的边处理,直到sum <= S。(我只想得到这么多了,莫得法太菜了呜呜呜。细节部分还一直处理不好,嗐。)
  • 看了大佬博客才知道,原来还得将经过次数和权值分别存取,如果直接存cnt*val会有错(这个在大佬2博客中有提到)。
  • 大佬1博客代码比较简洁清晰,大佬2博客思路比较详细。

代码实现:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e5 + 5;

int t, n, s;

struct edge{
    int v, w;
};

struct node{
    int cnt, val;
    bool operator< (const node it) const{
        return val*cnt-(val/2)*cnt < it.val*it.cnt - (it.val/2)*it.cnt;
    }
};

vector<vector<edge>> g;
vector<int> cnt, val;

void dfs(int u, int fa){
    if(fa != -1 && g[u].size() == 1) cnt[u] = 1;
    for(auto it : g[u]){
        if(it.v == fa) continue;
        val[it.v] = it.w;
        dfs(it.v, u);
        cnt[u] += cnt[it.v];
    }
}

signed main()
{
    IOS;

    cin >> t;
    while(t --){
        cin >> n >> s;
        g = vector<vector<edge>>(n + 1);
        cnt = val = vector<int>(n + 1);
        for(int i = 1; i < n; i ++){
            int u, v, w; cin >> u >> v >> w;
            g[u].push_back({v, w});
            g[v].push_back({u, w});
        }
        dfs(1, -1);
        priority_queue<node> q;
        int sum = 0;
        for(int i = 2; i <= n; i ++){
            sum += cnt[i]*val[i];
            q.push({cnt[i], val[i]});
        }
        int ans = 0;
        while(sum > s){
            ans ++;
            node now = q.top(); q.pop();
            sum -= now.val*now.cnt-(now.val/2)*now.cnt;
            q.push({now.cnt, now.val/2});
        }
        cout << ans <<endl;
    }

    return 0;
}

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页