Cod sursa(job #2052144)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 30 octombrie 2017 08:35:10
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

class bipart
{
public:
    bipart(int n, int m)
    {
        this->n = n;
        this->m = m;
        edges.resize(n + 1);
        viz.resize(n + 1);
        to.resize(n + 1);
        from.resize(m + 1, 0);
    }
    void AddEdge(int x, int y)
    {
        edges[x].push_back(y);
    }
    void GetCuplaj(vector<pair<int, int> > &ret)
    {
        fill(to.begin(), to.end(), 0);
        fill(from.begin(), from.end(), 0);
        bool cuplat = true;
        while(cuplat)
        {
            cuplat = false;
            fill(viz.begin(), viz.end(), false);
            for(int i = 1; i <= n; ++i)
                if(to[i] == 0 && cupleaza(i))
                    cuplat = true;
        }
        for(int i = 1; i <= n; ++i)
            if(to[i] != 0)
                ret.push_back({i, to[i]});
    }
private:
    bool cupleaza(int nod)
    {
        if(viz[nod])
            return false;
        viz[nod] = true;
        for(auto v:edges[nod])
            if(from[v] == 0)
            {
               to[nod] = v;
               from[v] = nod;
               return true;
            }
        for(auto v:edges[nod])
            if(cupleaza(from[v]))
            {
                to[nod] = v;
                from[v] = nod;
                return true;
            }
        return false;
    }
    vector<bool> viz;
    vector<vector<int> > edges;
    vector<int> to;
    vector<int> from;
    int n, m;
};

int main()
{
    ifstream in("cuplaj.in");
    int n, m, e;
    in >> n >> m >> e;
    bipart graf(n, m);
    int x, y;
    while(e--)
    {
        in >> x >> y;
        graf.AddEdge(x, y);
    }
    in.close();

    vector<pair<int, int> > rasp;
    graf.GetCuplaj(rasp);

    ofstream out("cuplaj.out");
    out << rasp.size() << "\n";
    for(auto &x:rasp)
        out << x.first << " " << x.second << "\n";
    out.close();
    return 0;
}