Cod sursa(job #1113828)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 20 februarie 2014 22:26:53
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.75 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

class BipartiteGraph {
  public:
    static const int NIL = -1;

    BipartiteGraph(const int _white = 0, const int _black = 0):
      white(_white),
      black(_black),
      edges(vector< vector<int> >(_white + _black, vector<int>())) {}

    int V() const {
        return white + black;
    }

    int White() const {
        return white;
    }

    int Black() const {
        return black;
    }

    vector<int>::const_iterator EdgesBegin(const int x) const {
        return edges[x].begin();
    }

    vector<int>::const_iterator EdgesEnd(const int x) const {
        return edges[x].end();
    }

    void AddEdge(const int x, const int y) {
        edges[x].push_back(y);
        edges[y].push_back(x);
    }

    vector< pair<int, int> > GetMaximumMatching() const {
        vector<int> vertexPair = vector<int>(V(), NIL);
        for (bool change = true; change; ) {
            change = false;
            vector<bool> used = vector<bool>(white, false);
            for (int x = 0; x < white; ++x)
                if (vertexPair[x] == NIL)
                    change |= PairUp(x, vertexPair, used);
        }
        vector< pair<int, int> > matching;
        for (int x = 0; x < white; ++x)
            if (vertexPair[x] != NIL)
                matching.push_back(make_pair(x, vertexPair[x]));
        return matching;
    }

  private:
    int white, black;
    vector< vector<int> > edges;

    bool PairUp(const int x, vector<int> &vertexPair, vector<bool> &used) const {
        if (x == NIL || used[x])
            return false;
        used[x] = true;
        for (vector<int>::const_iterator y = edges[x].begin(); y != edges[x].end(); ++y) {
            if (vertexPair[*y] == NIL || PairUp(vertexPair[*y], vertexPair, used)) {
                vertexPair[x] = *y;
                vertexPair[*y] = x;
                return true;
            }
        }
        return false;
    }
};

BipartiteGraph G;
vector< pair<int, int> > Matching;

void Solve() {
    Matching = G.GetMaximumMatching();
}

void Read() {
    ifstream cin("cuplaj.in");
    int white, black, edges;
    cin >> white >> black >> edges;
    G = BipartiteGraph(white, black);
    for (; edges > 0; --edges) {
        int x, y;
        cin >> x >> y;
        G.AddEdge(--x, (--y) + white);
    }
    cin.close();
}

void Print() {
    ofstream cout("cuplaj.out");
    cout << int(Matching.size()) << "\n";
    for (int i = 0; i < int(Matching.size()); ++i)
        cout << Matching[i].first + 1 << " " << Matching[i].second - G.White() + 1 << "\n";
    cout.close();
}

int main() {
    Read();
    Solve();
    Print();
    return 0;
}