【发布时间】:2012-01-06 18:30:47
【问题描述】:
我正在尝试用 C++ 实现 Ford Fulkerson 算法。
但是,我的find_edge 函数有问题。当我在my_alg 中调用此函数时,它会选择正确的边缘,然后在my_alg 中增加流。它选择右边缘并增加其流量 (flow),但是当我再次调用 find_edge 函数时,流量并未按应有的方式增加。
这导致我的算法无限循环。可能我对指针做错了什么。你可以在下面看到我的代码。
//An object of this class represents an edge in the graph.
class Edge
{
private:
//Node *prev;
public:
int flow;
Edge(Node *firstNode, Node *secNode, unsigned inCost) {
orgNode = firstNode;
dstNode = secNode;
bridge_capacity = inCost;
}
Edge() {
flow=0;
}
};
//An object of this class holds a vertex of the graph
class Node
{
public:
Node *prev;
vector<Edge>& getAdjNodeList() {
return adjNodeList;
}
};
Edge *find_edge(Graph *g,Node *from,Node *to) {
vector<Edge> b=from->getAdjNodeList();
for(int i=0;i<b.size();i++) {
if(b[i].getDstNode()==to)
return (&b[i]);
}
return NULL;
}
int my_alg(Graph *as,Node *source,Node *sink){
Edge *find_edge();
int max_flow=0;
while(bfs(as,source,sink)) {
Node *b=as->nodeList[num_isl];
int inc=100000000;
while(b->prev!=NULL) {
Edge *bok=find_edge(as,b->prev,b);
inc=min(inc,bok->get_bridge_capacity()-bok->flow);
b=b->prev;
}
b=as->nodeList[num_isl];
while(b->prev!=NULL){
Edge *bok = find_edge(as,b->prev,b);
bok->flow += inc; // This is the place the flow is incremented
bout << bok->flow; // Here, everything is alright.
bok = find_edge(as,b->prev,b);
cout << bok->flow; // However, this is is not the correct result.
}
max_flow+=inc;
}
return max_flow;
}
【问题讨论】:
-
在my_alg的开头,你为什么要做“Edge *find_edge();” ?
-
如果有帮助,我会收到此错误:错误 C2660: 'find_edge' : function does not take 3 parameters, but it is defined as : Edge *find_edge(Graph *g, Node *from , 节点 *to) , 三个参数
-
实际上我忘记删除 my_alg 中的 *find_edge()。我在尝试解决问题时添加了这一行。但它并没有改变任何东西
-
我没有收到任何错误,例如“find_edge”:函数不采用 3 个参数。
-
要获得好的答案,最好将代码减少到问题明确需要的部分。没有多少人会通读你所有的 300 行代码。此外,请务必查看代码的格式 - 这次我为您做了一些缩进,一旦经过同行评审,就可以看到。但是,通常这应该是您的工作。
标签: c++ algorithm graph-theory flow ford-fulkerson