Cod sursa(job #1396058)

Utilizator rootsroots1 roots Data 21 martie 2015 23:55:59
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <fstream>
#include <vector>
#include <cstring>

#define MAXV 10001

using namespace std;

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

int L, R, E;
vector <int> G[MAXV];
int matchOfL[MAXV];
int matchOfR[MAXV];
int maxMatch = 0;
bool used[MAXV];

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);
    }
}

inline bool dfs(int node) {
    if (used[node]) return false;
    used[node] = true;
    
    for (vector <int>::iterator it = G[node].begin(); it != G[node].end(); ++ it) {
        if (matchOfR[*it] == 0) {
            matchOfL[node] = *it;
            matchOfR[*it] = node;
            
            return true;
        } else {
            bool isPath = dfs(matchOfR[*it]);
            
            if (isPath) {
                matchOfL[node] = *it;
                matchOfR[*it] = node;
                
                return true;
            }
        }
    }
    
    return false;
}

inline void bipartiteMatchingWithHopcroftKarpSimplified() {
    bool foundPath = false;
    
    do {
        foundPath = false;
        memset(used, false, sizeof(used));
        
        for (int root = 1; root <= L; ++ root) {
            if (matchOfL[root] == 0) {
                bool augmentedSomePath = dfs(root);
                
                if (augmentedSomePath) {
                    maxMatch ++;
                    foundPath = true;
                }
                
            }
        }
    } while (foundPath);
}

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

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