有向图弧表实现
我正在尝试将图形实现为弧列表,虽然这种实现的工作效率非常糟糕,但我错过了什么导致它如此缓慢?时间被测量为寻找来自/到每个节点的弧的平均值。
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 outgoing 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;
}
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 outgoing 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你的实现是最糟糕的:为了找到输入/输出边缘,你必须遍历整个图表。
你真的需要一个弧列表吗?通常邻接表的效率要高得多。
邻接表的一个简单实现是保持向量 > 。弧,其中弧的大小是节点数。
给定一个节点 u,arcs[u] 给出所有的出边。您也可以弄清楚如何针对边缘进行优化。
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.