C - Shorten Diameter
Problem Statement
Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K.
You are given an undirected tree with N vertices numbered 1 through N. For each i(1≦i≦N−1), there is an edge connecting vertices Ai and Bi.
You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected.
Find the minimum number of vertices that you need to remove in order to produce a good tree.
Constraints
- 2≦N≦2000
- 1≦K≦N−1
- 1≦Ai≦N,1≦Bi≦N
- The graph defined by Ai and Bi is a tree.
Input
The input is given from Standard Input in the following format:
N K A1 B1 A2 B2 : AN−1 BN−1
Output
Print the minimum number of vertices that you need to remove in order to produce a good tree.
Sample Input 1
6 2 1 2 3 2 4 2 1 6 5 6
Sample Output 1
2
The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.
Sample Input 2
6 5 1 2 3 2 4 2 1 6 5 6
Sample Output 2
0
Since the given tree is already good, you do not need to remove any vertex.
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 #include <cmath> 5 #include <cstring> 6 using namespace std; 7 const int N = 2010; 8 vector<int> edge[N]; 9 pair<int,int> e[N]; 10 bool vis[N]; 11 int cnt; 12 void dfs(int n,int k){ 13 vis[n]=1;cnt++; 14 if(k==0) return ; 15 for(int i=0;i<edge[n].size();i++){ 16 if(!vis[edge[n][i]]) dfs(edge[n][i],k-1); 17 } 18 } 19 int main(){ 20 int n,k;cin>>n>>k; 21 for(int i=1;i<=n-1;i++){ 22 int a,b;cin>>a>>b; 23 e[i].first=a;e[i].second=b; 24 edge[a].push_back(b); 25 edge[b].push_back(a); 26 } 27 int ans=n; 28 if(k&1){ 29 for(int i=1;i<=n-1;i++){ 30 cnt=0; 31 memset(vis,0,sizeof vis); 32 vis[e[i].second]=1; 33 dfs(e[i].first,k/2); 34 dfs(e[i].second,k/2); 35 int tmp=n-cnt; 36 ans=min(tmp,ans); 37 } 38 }else{ 39 for(int i=1;i<=n;i++){ 40 cnt=0; 41 memset(vis,0,sizeof vis); 42 dfs(i,k/2); 43 int tmp=n-cnt; 44 ans=min(tmp,ans); 45 } 46 } 47 cout<<ans<<endl; 48 }