簡體   English   中英

如何獲得有向圖上給定頂點的輸入邊?

[英]How can I get input edges of a given vertex on a directed graph?

我有一個有向圖,我想獲取給定頂點的父代。

假設我有圖1 -> 2 -> 3 ,我握住了頂點2 ,我想得到頂點1

我的頂點和圖形定義:

struct TreeVertex   {  int id = -1;  };

typedef boost::adjacency_list<
    boost::vecS,
    boost::vecS,
    boost::directedS,
    TreeVertex
    > tree_t;

MVCE顯示了我想要實現的目標(請參見此處的在線內容 ):

int main() {
    tree_t tree;
    auto v1 = boost::add_vertex( tree );    
    auto v2 = boost::add_vertex( tree );    
    auto v3 = boost::add_vertex( tree );    
    boost::add_edge( v1, v2, tree );
    boost::add_edge( v2, v3, tree );

// attempt to get the input edge of v2
    auto pair_it_edge = boost::in_edges( v2, tree ); // FAILS TO BUILD  
    auto v = boost::source( *pair_it_edge.first ); // should be v1
}

另一個答案建議將圖形轉換為BidirectionalGraph但我需要保持其定向。

問題:這可能嗎? 如何獲取v2的傳入邊緣,以便提取v1

如果不使用雙向圖,則將必須對所有節點進行蠻力搜索,以查找以頂點2為子節點的節點。

#include <iostream>
#include <boost/graph/adjacency_list.hpp>
using namespace std;
   using namespace boost;

struct TreeVertex   {  int id = -1;  };

typedef boost::adjacency_list<
    boost::vecS,
    boost::vecS,
    boost::directedS,
    TreeVertex
    > tree_t;

    tree_t tree;


int main() {


    auto v1 = boost::add_vertex( tree );    
    auto v2 = boost::add_vertex( tree );    
    auto v3 = boost::add_vertex( tree );    
    boost::add_edge( v1, v2, tree );
    boost::add_edge( v2, v3, tree );

    int looking_for = 2;

    typename graph_traits < tree_t >::out_edge_iterator ei, ei_end;
    for( int v = 0; v < num_edges( tree ); v++ )
    for (boost::tie(ei, ei_end) = out_edges(v, tree); ei != ei_end; ++ei) {
    auto source = boost::source ( *ei, tree );
    auto target = boost::target ( *ei, tree );
    if( target == looking_for )
        std::cout << "There is an edge from " << source <<  " to " << target << std::endl;

// create an inverted edge tree to search for parents
tree_t invtree;
boost::add_edge( v2, v1, invtree );
boost::add_edge( v1, v3, invtree );
typename graph_traits < tree_t >::adjacency_iterator it, it_end;
for (tie(it, it_end) = adjacent_vertices(v2, invtree ); it != it_end; ++it) 
{
    std::cout << "There is an inv edge from " <<  v2
        << " to " << *it << std::endl;
}


    return 0;
}

創建帶有倒置邊緣的臨時樹作為圖形的“副本”以簡化對父級的搜索可能是值得的。 在代碼末尾添加了類似invtree的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM