//
// main.cpp
// Bipartite matching
//
// Created by Longxiang Lyu on 8/15/16.
// Copyright © 2016 Longxiang Lyu. All rights reserved.
//
// max cardinality matching can be solved by max-flow
// given a bipartite graph G = (L V R, E)
// create G' = (L V R V {s, t}, E')
// direct all edges from L to R, and assign infinite capacity
// add source s, and unit capacity edges from s to each node in L
// add sink t, and unit capacity edges from each node in R to t
// reference:
// http://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/07NetworkFlowII-2x2.pdf
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int inf = 10000;
bool bfs(vector<vector<int>> &rGraph, vector<int> &parent, int s, int t)
{
int V = static_cast<int>(rGraph.size());
vector<int> visited(V, 0); // mark all vertices as unvisited
queue<int> q;
q.push(s);
visited[s] = 1; // mark source vertex as visited
parent.clear();
parent.resize(V);
parent[s] = -1;
while (!q.empty())
{
int u = q.front(); // get the first element
q.pop();
for (int v = 0; v != V; ++v)
{
if (visited[v] == 0 && rGraph[u][v] > 0)
{
q.push(v);
parent[v] = u;
visited[v] = 1;
}
}
}
return visited[t] == 1;
}
int fordFulkerson(vector<vector<int>> &graph, int s, int t)
{
int u, v;
vector<vector<int>> rGraph = graph;
vector<int> parent;
int max_flow = 0; // initially zero flow
while (bfs(rGraph, parent, s, t))
{
int bottleneck = INT_MAX;
// get the bottleneck capacity of the augment path
for (v = t; v != s; v = parent[v])
{
u = parent[v];
bottleneck = min(bottleneck, rGraph[u][v]);
}
for (v = t; v != s; v = parent[v])
{
u = parent[v];
rGraph[u][v] -= bottleneck;
rGraph[v][u] += bottleneck;
}
max_flow += bottleneck;
}
return max_flow;
}
vector<vector<int>> buildDirected(const vector<vector<int>> &graph)
{
int sz = static_cast<int>(graph.size());
int V = 2 * sz + 2;
vector<vector<int>> ret(V, vector<int>(V, 0));
for (int i = 0; i != sz; ++i)
for (int j = 0; j != sz; ++j)
if (graph[i][j])
ret[i + 1][j + sz + 1] = inf;
fill(ret[0].begin() + 1, ret[0].begin() + sz + 1, 1);
for (int i = sz + 1; i != V - 1; ++i)
ret[i][V - 1] = 1;
return ret;
}
int main(int argc, const char * argv[])
{
// insert code here...
vector<vector<int>> graph = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {0, 1, 0, 0, 1}};
auto ret = buildDirected(graph);
auto n = fordFulkerson(ret, 0, (static_cast<int>(graph.size()) * 2 + 1));
cout << "max cardinality matching: "
<< n << endl;
string s = (n == graph.size()) ? "Perfect" : "Not Perfect";
cout << s + " Matching" << endl;
return 0;
}
Max bipartite matching with Ford-Fulkerson algorithm
最新推荐文章于 2022-11-29 13:47:27 发布