链接: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;
}