Cod sursa(job #2365170)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 4 martie 2019 12:19:05
Problema Cuplaj maxim in graf bipartit Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 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);
    }
    void AddEdge(int x, int y)
    {
        edges[x].push_back(y);
    }
    void GetCuplaj(vector<pair<int, int> > &ret)
    {
        vector<int> to(n+1), from(m+1);
        bool cuplat = true;
        while(cuplat)
        {
            cuplat = false;
            for(int i = 1; i <= n; ++i)
                if(to[i] == 0 && cupleaza(i, to, from))
                    cuplat = true;
        }
        for(int i = 1; i <= n; ++i)
            if(to[i] != 0)
                ret.push_back({i, to[i]});
    }
private:
    bool cupleaza(int nod, vector<int> &to, vector<int> &from)
    {
        for(auto v:edges[nod])
            if(from[v] == 0)
            {
               to[nod] = v;
               from[v] = nod;
               return true;
            }
        for(auto v:edges[nod])
            if(from[v] != nod && cupleaza(from[v], to, from))
            {
                to[nod] = v;
                from[v] = nod;
                return true;
            }
        return false;
    }
    vector<vector<int> > edges;
    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;
}