Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Maximum bipartite matching
- // Index from 1
- // Find max independent set:
- // for(i = 1 → M) if (mat.matchL[i] > 0) {
- // if (mat.dist[i] < inf) {
- // for(j = 1 → N) if (ke[i][j]) right.erase(j); }
- // else left.erase(i);
- // }
- // Find vertices that belong to all maximum matching:
- // - L = vertices not matched on left side --> BFS from these vertices
- // (left --> right: unmatched edges, right --> left: matched edges)
- // reachable vertices on left side --> not belong to some maximum matching
- // - Do similar for right side
- // Find minimum vertex cover:
- // L = vertices not matched on left side --> BFS from these vertices
- // (left --> right: unmatched edges, right --> left: matched edges)
- // reachable vertices on left side --> not belong to some maximum matching
- // Let U be all visited vertices. from left side, take vertices that are not in U, from right side , take vertices that are in U;
- // all taken vertices must have a match
- struct Matching {
- int n;
- vector<int> matchL, matchR, dist;
- vector<bool> seen;
- vector< vector<int> > ke;
- Matching(int n) : n(n), matchL(n+1), matchR(n+1), dist(n+1), seen(n+1, false), ke(n+1) {}
- void addEdge(int u, int v) {
- ke[u].push_back(v);
- }
- bool bfs() {
- queue<int> qu;
- for(int u = 1; u <= n; ++u)
- if (!matchL[u]) {
- dist[u] = 0;
- qu.push(u);
- } else dist[u] = inf;
- dist[0] = inf;
- while (!qu.empty()) {
- int u = qu.front(); qu.pop();
- for(__typeof(ke[u].begin()) v = ke[u].begin(); v != ke[u].end(); ++v) {
- if (dist[matchR[*v]] == inf) {
- dist[matchR[*v]] = dist[u] + 1;
- qu.push(matchR[*v]);
- }
- }
- }
- return dist[0] != inf;
- }
- bool dfs(int u) {
- if (u) {
- for(__typeof(ke[u].begin()) v = ke[u].begin(); v != ke[u].end(); ++v)
- if (dist[matchR[*v]] == dist[u] + 1 && dfs(matchR[*v])) {
- matchL[u] = *v;
- matchR[*v] = u;
- return true;
- }
- dist[u] = inf;
- return false;
- }
- return true;
- }
- int match() {
- int res = 0;
- while (bfs()) {
- for(int u = 1; u <= n; ++u)
- if (!matchL[u])
- if (dfs(u)) ++res;
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment