[英]What is the most efficient way to get all elements from a ProtoBuf RepeatedField?
[英]What is the most efficient way to get all subtrees from node array and edge vector?
假設像這樣的數組有節點,向量的無向邊是這樣的:
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));
其中數組的每個元素都是值, n
是數組的數量。 在上面的代碼之后,有兩個邊緣。 一個從0到2。另一個從2到4。這些數字表示數組的索引。 在這種情況下,最大子樹的大小顯然是0-2-4的3,最小子樹的大小是1。
我如下解決了這個問題:
edges
矢量 edges
一種排列 但是,我不確定這是否有效。 我如何獲得像這樣的問題域中的所有子樹? 有什么通用有效的方法嗎?
我使用基於邊緣信息的BFS(廣度優先搜索)解決了這個問題。 為了避免制作循環圖並將節點保留為樹,我使用set
。 在搜索之前,我也會應用sort
。 減少時間復雜度很有用。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.