Cod sursa(job #2712689)

Utilizator Marius7122FMI Ciltea Marian Marius7122 Data 26 februarie 2021 12:24:43
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int N = 10005;

int n, m, e;
vector<int> g[N], isLeftCoupled, isRightCoupled;
vector<bool> vis;

bool match(int node)
{
    if(vis[node])
        return false;
    vis[node] = true;

    for(int vec : g[node])
    {
        if(isRightCoupled[vec] == -1)
        {
            isRightCoupled[vec] = node;
            isLeftCoupled[node] = vec;
            return true;
        }
    }

    for(int vec : g[node])
    {
        if(match(isRightCoupled[vec]))
        {
            isRightCoupled[vec] = node;
            isLeftCoupled[node] = vec;
            return true;
        }
    }

    return false;
}

int main()
{
    fin >> n >> m >> e;
    isLeftCoupled.resize(n + 1, -1);
    isRightCoupled.resize(m + 1, -1);

    for(int i = 0; i < e; i++)
    {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
    }

    bool ok;
    do
    {
        vis.assign(n + m + 1, false);
        ok = false;
        for(int i = 1; i <= n; i++)
            if(isLeftCoupled[i] == -1 && match(i))
                ok = true;
    }while(ok);

    int coupled = 0;
    for(int i = 1; i <= n; i++)
        if(isLeftCoupled[i] != -1)
            coupled++;

    fout << coupled << '\n';
    for(int i = 1; i <= n; i++)
        if(isLeftCoupled[i] != -1)
        {
            fout << i << ' ' << isLeftCoupled[i] << '\n';
        }

    fin.close();
    fout.close();
    return 0;
}