Cod sursa(job #1395737)

Utilizator rootsroots1 roots Data 21 martie 2015 13:59:43
Problema Cuplaj maxim in graf bipartit Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.35 kb
#include <fstream>
#include <vector>
#include <queue>

#define MAXV 10001

using namespace std;

ifstream in("cuplaj.in");
ofstream out("cuplaj.out");

int L, R, E;
vector <int> G[2 * MAXV];
int match[2 * MAXV];
int father[2 * MAXV];
bool isMarked[2 * MAXV];
int root[2 * MAXV];
int path;
int maxMatch = 0;

inline void readAndBuild() {
    in >> L >> R >> E;
    
    int x, y;
    for (int e = 0; e < E; ++ e) {
        in >> x >> y;
        
        G[x].push_back(y + L);
        G[y + L].push_back(x);
    }
}

inline bool findAugmentingPath() {
    queue <int> qF;
    
    for (int node = L + R; node > 0; -- node) {
        if (!match[node]) {
            qF.push(node);
            father[node] = node;
            root[node] = node;
        } else {
            father[node] = -1;
            root[node] = -1;
        }
        
        isMarked[node] = false;
    }
    
    for (int node = qF.front(); !qF.empty(); node = qF.front()) {
        qF.pop();
        
        for (vector <int>::iterator it = G[node].begin(); it != G[node].end(); ++ it) {
            if (match[*it] != node) {
                if (match[*it] != 0) {
                    father[*it] = node;
                    father[match[*it]] = *it;
                    
                    root[*it] = root[node];
                    root[match[*it]] = root[node];
                    
                    if (!isMarked[match[*it]]) {
                        qF.push(node);
                        isMarked[match[*it]] = true;
                    }
                } else {
                    father[root[*it]] = node;
                    path = *it;
                    
                    return true;
                }
            }
        }
    }
    
    return false;
}

inline void bipartiteMatchingWithEdmondsBlossom() {
    for (int isPath = findAugmentingPath(); isPath; isPath = findAugmentingPath()) {
        for (int node = path; father[node] != node; node = father[father[node]]) {
            match[node] = father[node];
            match[father[node]] = node;
        }
        
        maxMatch ++;
    }
}

inline void printResult() {
    out << maxMatch << '\n';
    for (int i = 1; i <= L; ++ i)
        if (match[i]) {
            out << i << ' ' << match[i] - L << '\n';
        }
}

int main() {
    readAndBuild();
    bipartiteMatchingWithEdmondsBlossom();
    printResult();
    
    return 0;
}