匈牙利算法(也称为增广路径算法)是一种解决二分图最大匹配问题的经典算法。以下是用C++实现匈牙利算法的示例代码:
#include <iostream>
#include <vector>
using namespace std;
// 使用DFS查找增广路径
bool dfs(vector<vector<int>>& graph, int u, vector<bool>& visited, vector<int>& match) {
int m = graph.size();
int n = graph[0].size();
for (int v = 0; v < n; ++v) {
if (graph[u][v] && !visited[v]) {
visited[v] = true;
// 如果v没有匹配或者可以找到增广路径
if (match[v] == -1 || dfs(graph, match[v], visited, match)) {
match[v] = u;
return true;
}
}
}
return false;
}
// 计算二分图的最大匹配数
int hungarian(vector<vector<int>>& graph) {
int m = graph.size();
int n = graph[0].size();
vector<int> match(n, -1); // 存储匹配信息,match[i]表示右侧第i个节点的匹配节点编号
int count = 0; // 最大匹配数
for (int u = 0; u < m; ++u) {
vector<bool> visited(n, false); // 记录每个节点的访问状态
if (dfs(graph, u, visited, match)) {
count++;
}
}
return count;
}
// 测试
int main() {
vector<vector<int>> graph = {
{1, 0, 1, 0},
{1, 0, 0, 0},
{0, 1, 1, 1},
{0, 0, 1, 0}
};
int maxMatching = hungarian(graph);
cout << "Maximum matching: " << maxMatching << endl;
return 0;
}
在上面的示例代码中,graph
是一个表示二分图的邻接矩阵,其中graph[i][j]
表示左侧第i
个节点和右侧第j
个节点之间是否有边。函数hungarian
计算二分图的最大匹配数,它调用dfs
函数来查找增广路径。最后,通过调用hungarian
函数来测试匈牙利算法并输出最大匹配数。
请注意,这只是匈牙利算法的一种简单实现方式,实际应用中可能需要根据具体情况进行适当的修改和优化。