找到从节点到距离它最远的节点的距离

时间:2013-10-20 20:01:07

标签: c++ boost c++11 nodes longest-path

我需要在最小生成树中完成从所有节点到距离它最远的节点的距离。到目前为止我已经做到了这一点,但我不知道从节点找到最长的距离。

#include<iostream>
#include<boost/config.hpp>
#include<boost/graph/adjacency_list.hpp>
#include<boost/graph/kruskal_min_spanning_tree.hpp>
#include<boost/graph/prim_minimum_spanning_tree.hpp>

using namespace std;
using namespace boost;

int main()
{
typedef adjacency_list< vecS, vecS, undirectedS, property <vertex_distance_t,int>, property< edge_weight_t, int> > Graph;
int test=0,m,a,b,c,w,d,i,no_v,no_e,arr_w[100],arr_d[100];
cin>>test;
m=0;
while(m!=test)
{
cin>>no_v>>no_e;
Graph g(no_v);
property_map <Graph, edge_weight_t>:: type weightMap=get(edge_weight,g);
bool bol;
graph_traits<Graph>::edge_descriptor ed;

for(i=0;i<no_e;i++)
{
cin>>a>>b>>c;
tie(ed,bol)=add_edge(a,b,g);
weightMap[ed]=c;
}

property_map<Graph,edge_weight_t>::type weightM=get(edge_weight,g);
property_map<Graph,vertex_distance_t>::type distanceMap=get(vertex_distance,g);
property_map<Graph,vertex_index_t>::type indexMap=get(vertex_index,g);

vector< graph_traits<Graph>::edge_descriptor> spanning_tree;

kruskal_minimum_spanning_tree(g,back_inserter(spanning_tree));

vector<graph_traits<Graph>::vector_descriptor>p(no_v);

prim_minimum_spanning_tree(g,0,&p[0],distancemap,weightMap,indexMap,default_dijkstra_visitor());



w=0;

for(vector<graph_traits<Graph>::edge_descriptor>::iterator eb=spanning_tree.begin();eb!=spanning_tree.end();++eb) //spanning tree weight
{
w=w+weightM[*eb];
}

arr_w[m]=w;
d=0;

graph_traits<Graph>::vertex_iterator vb,ve;

for(tie(vb,ve)=vertices(g),.

arr_d[m]=d;
m++;
}

for( i=0;i<test;i++)
{
cout<<arr_w[i]<<endl;
}

return 0;
}

如果我有一个带有节点1 2 3 4的生成树,我需要找到生成树中距离1 2 3 4的最长距离(并且最长距离可以包含许多边缘,而不仅仅是一个)。

1 个答案:

答案 0 :(得分:0)

我不会给你准确的代码如何做到这一点,但我会告诉你并知道如何做到这一点。

首先,MST(最小生成树)的结果是所谓的树。想想定义。可以说它是一个图表,其中存在从每个节点到每个其他节点的路径,并且没有循环。或者你可以说给定的图是树,如果每个u和v只存在一个从顶点u到v的路径。

根据定义,您可以定义以下

function DFS_Farthest (Vertex u, Vertices P)
begin
    define farthest is 0
    define P0 as empty set
    add u to P

    foreach v from neighbours of u and v is not in P do
    begin
        ( len, Ps ) = DFS_Farthest(v, P)
        if L(u, v) + len > farthest then
        begin
            P0 is Ps union P
            farthest is len + L(u, v)
        end
    end

    return (farthest, P0)
end

然后你会在图形调用DFS_Farthest(v, empty set)中找到每个顶点v,并且它会给你(最远的,P),其中最远的节点距离是最远的节点,P是顶点的集合。你可以重建从v到最远顶点的路径。

现在来描述一下它在做什么。首先是签名。第一个参数来自你想知道最远的顶点。第二个参数是一组禁止顶点。所以它说&#34;嘿,给我从v到最远顶点的最长路径,所以P的顶点不在那条路径中#34;。

接下来有foreach这个问题。在那里,您正在寻找距离当前顶点最远的顶点而不访问P中已经存在的顶点(当前顶点已经存在)。如果您发现路径较长,则目前找不到farthestP0。请注意,L(u, v)是边{u,v}的长度。

最后,您将返回那些长度和禁止的顶点(这是到最远顶点的路径)。

这只是简单的DFS(深度优先搜索)算法,您可以记住已访问过的顶点。

现在关于时间的复杂性。假设您可以在O(1)中获得给定顶点的邻居(取决于您拥有的数据结构)。函数只访问每个顶点一次。所以它至少是O(N)。要知道每个顶点的最远顶点,必须为每个顶点调用此函数。这使您解决问题的时间复杂度至少为O(n ^ 2)。

我的猜测是,使用动态编程可能会有更好的解决方案,但这只是猜测。通常在图中找到最长路径是NP难问题。这让我怀疑可能没有任何明显更好的解决方案。但这是另一种猜测。