Cod sursa(job #1396045)

Utilizator rootsroots1 roots Data 21 martie 2015 23:35:24
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 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]; // i in L, matchOfL[i] in R
int matchOfR[MAXV]; // i in R, matchOfR[i] in L
bool used[MAXV];
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);
        
        // I do not need to push the reverse edge into the graph
        // because when finding an alternating (augmenting) path
        // the nodes that are on R side, always follow an edge that is in M
        // and because there is only on edge in M with some vertex v on it
        // we know that there is only one way to go back on L side
    }
}

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 bipartiteMatchingEdmondsBlossomSimplified() {
    bool foundPath = true;
    
    while (foundPath) {
        foundPath = false;
        
        memset(used, false, sizeof(used));
        
        for (int root = 1; root <= L; ++ root) {
            if (matchOfL[root] == 0) {
                foundPath = dfs(root);
                
                if (foundPath) {
                    maxMatch ++;
                    break;
                }
            }
        }
    }
}

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

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