// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
#define N 20
// Function to perform DFS Traversal
int dfs(vector<bool> &visited, int s,
int &K, int &removals,
vector<int> &removed_nodes,
vector<vector<int>> &adj)
{
// Mark the node as true
visited[s] = true;
int nodes = 1;
// Traverse adjacency list
// of child node
for(int child : adj[s])
{
// If already visited then
// omit the node
if (visited[child])
continue;
// Add number of nodes
// in subtree
nodes += dfs(visited, child, K,
removals, removed_nodes,
adj);
}
if (nodes > K)
{
// Increment the count
removals++;
removed_nodes.push_back(s);
nodes = 0;
}
// Return the nodes
return nodes;
}
// Function to add edges in graph
void addEdge(vector<vector<int>> &adj,
int a, int b)
{
adj[a].push_back(b);
adj[b].push_back(a);
}
// Function that finds the number
// of nodes to be removed such that
// every subtree has size at most K
void findRemovedNodes(vector<bool> &visited, int K,
int &removals,
vector<int> &removed_nodes,
vector<vector<int>> &adj)
{
// Function Call to find the
// number of nodes to remove
dfs(visited, 1, K, removals,
removed_nodes, adj);
// Print Removed Nodes
cout << "Number of nodes removed: "
<< removals << endl;
cout << "Removed Nodes: ";
for(int node : removed_nodes)
{
cout << node << " ";
}
}
// Driver Code
int main()
{
// Variables used to store data globally
vector<bool> visited(N);
int K;
int removals = 0;
vector<int> removed_nodes;
// Adjacency list representation of tree
vector<vector<int>> adj(N);
// Insert of nodes in graph
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 2, 4);
addEdge(adj, 2, 5);
addEdge(adj, 3, 6);
// Required subtree size
K = 3;
// Function Call
findRemovedNodes(visited, K, removals,
removed_nodes, adj);
return 0;
}
// This code is contributed by sanjeev2552