Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /********************************************************************
- * Maximum Matching in General Graph Edmonds' algorithm in O(V^3)
- * Index = 0 based
- * Minimum Edge Cover = Maximum Matching + # of nodes which are not matched
- ********************************************************************/
- #include<bits/stdc++.h>
- using namespace std;
- const int N = 105;
- int n;// number of node [0,n-1]
- vector<int> G[N];
- int match[N], p[N], base[N], q[N];
- bool used[N], blossom[N];
- int lca (int a, int b) {
- bool used[N] = { 0 };
- while(true) {
- a = base[a];
- used[a] = true;
- if (match[a] == -1) break;
- a = p[match[a]];
- }
- while( true ){
- b = base[b];
- if (used[b]) return b;
- b = p[match[b]];
- }
- }
- void mark_path (int v, int b, int children) {
- while (base[v] != b) {
- blossom[base[v]] = blossom[base[match[v]]] = true;
- p[v] = children;
- children = match[v];
- v = p[match[v]];
- }
- }
- int find_path (int root) {
- memset (used, 0, sizeof used);
- memset (p, -1, sizeof p);
- for (int i=0; i<n; ++i)
- base[i] = i;
- used[root] = true;
- int qh=0, qt=0;
- q[qt++] = root;
- while (qh < qt) {
- int v = q[qh++];
- for (size_t i=0; i < G[v].size(); ++i) {
- int to = G[v][i];
- if (base[v] == base[to] || match[v] == to) continue;
- if (to == root || match[to] != -1 && p[match[to]] != -1) {
- int curbase = lca (v, to);
- memset (blossom, 0, sizeof blossom);
- mark_path (v, curbase, to);
- mark_path (to, curbase, v);
- for (int i=0; i<n; ++i)
- if (blossom[base[i]]) {
- base[i] = curbase;
- if (!used[i]) {
- used[i] = true;
- q[qt++] = i;
- }
- }
- }
- else if (p[to] == -1) {
- p[to] = v;
- if (match[to] == -1)
- return to;
- to = match[to];
- used[to] = true;
- q[qt++] = to;
- }
- }
- }
- return -1;
- }
- int maxMatching() {
- memset(match,-1,sizeof(match));
- for (int i = 0; i < n; ++i) {
- if (match[i] == -1) {
- int v = find_path(i);
- while (v != -1) {
- int pv = p[v];
- int ppv = match[pv];
- match[v] = pv;
- match[pv] = v;
- v = ppv;
- }
- }
- }
- int matches = 0;
- for (int i = 0; i < n; ++i)
- if (match[i] != -1) {
- matches ++;
- }
- return matches / 2;
- }
Add Comment
Please, Sign In to add comment