Assume that there are nodes as array and undirected edges as vector like this:
int nodes[n] = {1, 2, 3, ... ,n };
vector<pair<int, int>> edges;
edges.push_back(std::make_pair(0, 2));
edges.push_back(std::make_pair(2, 4));
where each element of array is value and n
is the number of array. Following above code, there are two edges. One is from 0 to 2. The other one is from 2 to 4. These numbers indicate index of array. In this case, size of largest sub-tree is 3 that 0-2-4 and size of smallest sub-tree is 1 obviously.
I solved this like below:
edges
vector edges
However I am not sure this is efficient way. How can I get all sub-trees in the problem domain like this? is there any general and efficient way?
I solved this problem using BFS (Breadth First Search) based on edge information. To avoid making cyclic graph and keep nodes as tree, I use set
. And I also apply sort
before searching. It is useful to reduce time complexity.
void BFS(set<int> nodes, vector<pair<int,int>>& edges, vector<set<int>>& result) {
result.push_back(nodes);
int lastNode = *max_element(nodes.begin(), nodes.end());
auto findIt = find_if(edges.begin(), edges.end(), [](const pair<int, int>& element){ return element.first == lastNode});
if(findIt != edges.end()) {
nodes.insert((*findIt).second);
BFS(nodes, edges, result);
}
}
sort(edges.begin(), edges.end());
vector<set<int>> result;
for(auto it : edges) {
set<int> nodes;
nodes.insert((*it).first);
nodes.insert((*it).second);
BFS(nodes, edges, result);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.