CodeForces - 1042F Leaf Sets(启发式合并)
F. Leaf Sets
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an undirected tree, consisting of nn vertices.
The vertex is called a leaf if it has exactly one vertex adjacent to it.
The distance between some pair of vertices is the number of edges in the shortest path between them.
Let's call some set of leaves beautiful if the maximum distance between any pair of leaves in it is less or equal to kk.
You want to split all leaves into non-intersecting beautiful sets. What is the minimal number of sets in such a split?
Input
The first line contains two integers nn and kk (3≤n≤1063≤n≤106, 1≤k≤1061≤k≤106) — the number of vertices in the tree and the maximum distance between any pair of leaves in each beautiful set.
Each of the next n−1n−1 lines contains two integers vivi and uiui (1≤vi,ui≤n1≤vi,ui≤n) — the description of the ii-th edge.
It is guaranteed that the given edges form a tree.
Output
Print a single integer — the minimal number of beautiful sets the split can have.
Examples
input
Copy
9 3 1 2 1 3 2 4 2 5 3 6 6 7 6 8 3 9
output
Copy
2
input
Copy
5 3 1 2 2 3 3 4 4 5
output
Copy
2
input
Copy
6 1 1 2 1 3 1 4 1 5 1 6
output
Copy
5
Note
Here is the graph for the first example:
题意:能把叶子分成多少个集合,使得集合里的节点对之间的距离都小于等于K
解题思路:启发式合并思想
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const int MAXN = 1000005;
const int INF = 0x3f3f3f3f;
vector<int> G[MAXN];
vector<int> num[MAXN];
int ans=1;
int N,K;
int dfs(int u,int fa){
if(G[u].size()==1)
return 0;
for(auto &v:G[u]){
if(v==fa)
continue;
num[u].push_back(dfs(v,u)+1);
}
sort(num[u].begin(),num[u].end());
while(num[u].size()>=2){
if(num[u].back()+num[u][num[u].size()-2]<=K)
break;
++ans;
num[u].pop_back();
}
return num[u].back();
}
int main()
{
scanf("%d%d",&N,&K);
int u,v;
for(int i=0;i<N-1;i++){
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=N;i++){
if(G[i].size()>1){
dfs(i,0);
break;
}
}
cout<<ans<<endl;
return 0;
}