开发者

Digraph arc list implementation

开发者 https://www.devze.com 2023-02-24 09:45 出处:网络
I\'m trying to implement graph as the Arc List, and while this implementation works efficiency is horrible, anything i missed that\'s making it so slow? Time was measured as the average of looking for

I'm trying to implement graph as the Arc List, and while this implementation works efficiency is horrible, anything i missed that's making it so slow? Time was measured as the average of looking for arcs from/to each node.

struct Arc 
{
    int start;
    int end;
    Arc(int start,int end)
      : start(start),
        end(end)
    { }
};

typedef vector<Arc> ArcList;

class AListGraph
{
public:
    AListGraph(IMatrix* in); //Fills the data from Incidence Matrix
    bool IsE(int va,int vb); //checks if arc exists a->b
    int CountEdges(); //counts all the arcs
    int CountNext(int v); //counts all ou开发者_如何学JAVAtgoing arcs from v
    int CountPrev(int v); //counts all arcs incoming to v

private:
    ArcList L;
    int VCount;
};

//Cut out constructor for clarity

int AListGraph::CountEdges() 
{
    return L.size();
}

int AListGraph::CountNext(int v)
{
    int result=0;
    for(ArcList::iterator it =L.begin();it!=L.end();it++)
    {
        if(it->end==v)result++;
    }
    return result;
}

int AListGraph::CountPrev(int v)
{
    int result=0;
    for(ArcList::iterator it =L.begin();it!=L.end();it++)
    {
        if(it->start==v)result++;
    }
    return result;
}


Well, your implemention is worst possible : in order to find the in/out edges you have go across the whole graph.

Do you really need an arc list? Usually an adjacency list is much more efficient.

A naïve implementation of an adjacency list would be to keep an vector > arcs where the size of the arc is the number of nodes.

Given an node u, arcs[u] gives you all the out edges. You can figure out how to optimize it for in edges also.

0

精彩评论

暂无评论...
验证码 换一张
取 消