【发布时间】:2016-06-29 18:47:26
【问题描述】:
我正在尝试将以下算法实现为迭代算法,但我无法正确执行。有人可以帮我解决这个问题。它是一种二分匹配算法,我在将 bpm 函数转换为迭代函数时遇到了麻烦。
// A DFS based recursive function that returns true if a
// matching for vertex u is possible
bool bpm(bool bpGraph[M][N], int u, bool seen[], int matchR[])
{
// Try every job one by one
for (int v = 0; v < N; v++)
{
// If applicant u is interested in job v and v is
// not visited
if (bpGraph[u][v] && !seen[v])
{
seen[v] = true; // Mark v as visited
// If job 'v' is not assigned to an applicant OR
// previously assigned applicant for job v (which is matchR[v])
// has an alternate job available.
// Since v is marked as visited in the above line, matchR[v]
// in the following recursive call will not get job 'v' again
if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR))
{
matchR[v] = u;
return true;
}
}
}
return false;
}
// Returns maximum number of matching from M to N
int maxBPM(bool bpGraph[M][N])
{
// An array to keep track of the applicants assigned to
// jobs. The value of matchR[i] is the applicant number
// assigned to job i, the value -1 indicates nobody is
// assigned.
int matchR[N];
// Initially all jobs are available
memset(matchR, -1, sizeof(matchR));
int result = 0; // Count of jobs assigned to applicants
for (int u = 0; u < M; u++)
{
// Mark all jobs as not seen for next applicant.
bool seen[N];
memset(seen, 0, sizeof(seen));
// Find if the applicant 'u' can get a job
if (bpm(bpGraph, u, seen, matchR))
result++;
}
return result;
}
【问题讨论】:
-
这应该是使用堆栈从递归 DFS 到迭代的直接转换。
-
这看起来像是 How to implement depth first search for graph with non-recursive aprroach 的骗子。如果您认为不是,请详细说明原因,否则我将作为骗子关闭。
-
它的不同之处在于我们处理电流的方式将取决于其余递归 dfs 调用的输出。迭代算法处理当前节点并移动到下一个迭代。
标签: algorithm recursion graph matching bipartite