/560/I(dfs+二分)

链接:https://ac.nowcoder.com/acm/contest/560/I
来源:牛客网
 

题目描述

You have a tree with N nodes and N-1 edges. Each node has a weight. The i-th node's weight is Wi. 
Now you should divide the N nodes into K connected parts . Each part has at least one node.
The sum of all node's Wi in a part is X. The minimum X of all parts is Y. You need to calculate maximum Y.

输入描述:

The first line contains two integers N and K(1≤K≤N≤100000)(1≤K≤N≤100000).
Each of the following N-1 lines contain two integers x,y denoting there is an edge between x and y.
The next line N integers W1,W2,...WN(1≤Wi≤105)(1≤Wi≤105).

输出描述:

Print one integer -- the maximized Y.

示例1

输入

复制

5 3
1 2
1 3
2 4
2 5
1 2 3 4 5

输出

复制

4

代码:
 

#include <iostream>
#include <cstdio>
#include <limits.h>
#include <vector>
 
using namespace std;
const int N = 100100;
typedef long long LL;
LL temp[N], weight[N];
vector<int> points[N];
int n, k, cnt;
 
void dfs(int u, int fa, LL mid) {
    temp[u] = weight[u];
    for(auto &v : points[u]) {
        if(v != fa) {
            dfs(v, u, mid);
            temp[u] += temp[v];
        }
    }
    if(temp[u] >= mid) {
        cnt++;
        temp[u] = 0;
    }
}
 
bool check(LL mid) {
    cnt = 0;
    dfs(1, -1, mid);//可能只有1个点,所以要从1开始
    return cnt >= k;
}
void solve() {
    LL l = 1, r = 2e10;
//  cout <<r << endl;
    while(l < r) {
        LL mid = (l + r + 1) >> 1;
        if(check(mid) == false) r = mid -1;
        else l = mid;
    }
    cout << l << endl;
}
int main() {
    cin >> n >> k;
    for(int i = 1; i < n; i++) {
        int x, y;
        cin >> x >> y;
        points[x].push_back(y);
        points[y].push_back(x);
    }
    for(int i = 1; i <= n; i++)  cin >> weight[i];
    solve();
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值