CF 1436D Bandit in a City 树上贪心

原题链接

文章目录

题意

给定一棵树形结构,每个点上都有一定的人数,人只能往叶子节点跑,根节点有一个土匪,问土匪最少能抓到多少人。

分析

我们只需要让所有的人均匀地跑到叶子节点就可以了,因此对于每个节点都有一个最优方案,也就是当前子树人数/当前子树叶子节点数+(人数%叶子节点 ? 1 : 0),最后取一个max就可以了,比较水的一道题。

AC Code

#include <bits/stdc++.h>

#define ACM_LOCAL
#define fi first
#define se second
#define pb push_back
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 5e5 + 10, M = 5e5 + 10, INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int n, m, k, cnt;
ll sz[N], ans[N], a[N], res;
vector<int> g[N];

void dfs(int u) {
    ans[u] = a[u];
    if (g[u].empty()) sz[u] = 1;
    for (auto v : g[u]) {
        dfs(v);
        sz[u] += sz[v];
        ans[u] += ans[v];
    }
}

void count(int u) {
    res = max(res, ans[u] / sz[u] + (ans[u] % sz[u] ? 1 : 0));
    for (auto v : g[u]) {
        count(v);
    }
}

void solve() {
    int n; cin >> n;
    for (int i = 2; i <= n; i++) {
        int x; cin >> x;
        g[x].push_back(i);
    }
    for (int i = 1; i <= n; i++) cin >> a[i];
    dfs(1); count(1);
    cout << res << endl;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
#endif
    solve();
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值