Cod sursa(job #2256587)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 8 octombrie 2018 20:35:34
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>

#define MaxN 10005

std::ifstream InFile("cuplaj.in");
std::ofstream OutFile("cuplaj.out");

int E;

template <int NNodes>
class BipartiteGraph {
public:
    int N, M;

    inline void AddEdge(int x, int y) {
        Node[x].ADC.push_back(y);
    }

    bool PairUp(int Index) {
        if (Seen[Index]) return false;
        Seen[Index] = 1;

        for (int i=0; i<Node[Index].ADC.size(); ++i)
            if (!L[Node[Index].ADC[i]] || PairUp(L[Node[Index].ADC[i]])) {
                L[Node[Index].ADC[i]] = Index;
                R[Index] = Node[Index].ADC[i];
                return true;
            }
        return false;
    }

    void Match() {
        bool Check;
        do {
            Check = 0;
            for (int i=0; i<N; ++i)
                Seen[i+1] = 0;
            for (int i=0; i<N; ++i)
                if (!R[i+1])
                    Check |= PairUp(i+1);
        }   while(Check);
    }

    void Print() {
        int MatchesCount = 0;
        for (int i=0; i<N; ++i)
            if (R[i+1]) MatchesCount ++;
        OutFile << MatchesCount << '\n';
        for (int i=0; i<N; ++i)
            if (R[i+1])
                OutFile << i+1 << ' ' << R[i+1] << '\n';
    }

private:
    bool Seen[NNodes];
    int L[MaxN], R[MaxN];       // R[i] - cuplul nodului din stanga i ce se afla in dreapta

    struct GraphNode{
        std::vector <int> ADC;
    }   Node[NNodes];

};  BipartiteGraph <MaxN> Graph;

void Citire() {
    InFile >> Graph.N >> Graph.M >> E;
    for (int i=0, x, y; i<E; ++i)
        InFile >> x >> y,
        Graph.AddEdge(x, y);
}
void Rezolvare() {
    Graph.Match();
    Graph.Print();
}

int main()
{
    Citire();
    Rezolvare();

    return 0;
}