Cod sursa(job #1395820)

Utilizator rootsroots1 roots Data 21 martie 2015 15:53:11
Problema Cuplaj maxim in graf bipartit Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.69 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];
int dist[2 * MAXV];
int maxMatch = 0;
int firstPath, secondPath;

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 bfs() {
    queue <int> q;
    
    for (int node = L + R; node > 0; -- node) {
        if (match[node] == 0) {
            father[node] = node;
            dist[node] = 0;
            q.push(node);
        } else {
            father[node] = -1;
            dist[node] = -1;
        }
    }
    
    // when q is empty, q.front() throws exception
    // this loop avoids the case above
    for (int node; !q.empty(); q.pop()) {
        node = q.front();
        
        for (vector <int>::iterator it = G[node].begin(); it != G[node].end(); ++ it) {
            if ((match[*it] == node) == dist[node] % 2) {
                if (father[*it] == -1) {
                    father[*it] = node;
                    dist[*it] = dist[node] + 1;
                    q.push(*it);
                } else if (dist[*it] % 2 == dist[node] % 2) {
                    firstPath = node;
                    secondPath = *it;
                    
                    return true;
                }
            }
        }
    }
    
    return false;
}
inline void printResult() {
    out << maxMatch << '\n';
    for (int i = 1; i <= L; ++ i)
        if (match[i]) {
            out << i << ' ' << match[i] - L << '\n';
        }
}

inline void bipartiteMatchingWithEdmondsBlossom() {
    for (int existsAugmentingPath = bfs(); existsAugmentingPath; existsAugmentingPath = bfs()) {
        int parity = dist[firstPath] % 2;
        
        if (parity == 0) {
            match[firstPath] = secondPath;
            match[secondPath] = firstPath;
        }
        
        for (int node = firstPath, sw = parity; node != father[node]; node = father[node], sw = 1 - sw) {
            if (sw == 1) {
                match[node] = father[node];
                match[father[node]] = node;
            }
        }
        
        for (int node = secondPath, sw = parity; node != father[node]; node = father[node], sw = 1 - sw) {
            if (sw == 1) {
                match[node] = father[node];
                match[father[node]] = node;
            }
        }
        
        maxMatch ++;
//        printResult();
    }
}



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