Cod sursa(job #1917159)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 9 martie 2017 11:20:57
Problema Cuplaj maxim in graf bipartit Scor 32
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");

vector <int> ls[10005];
int lft[10005];         // cu ce nod din dreapta e cuplat nodul din stanga
int rgt[10005];         //    .......     stanga      .........     dreapta
int n, m, x, y, i, j, e, sol;
bool viz[10005];

bool cuplu(int x) {
    int l = ls[x].size(), i;
    if (viz[x] == 1)
        return 0;
    viz[x] = 1;
    for (i = 0; i < l; i++) {
        y = ls[x][i];
        //g<<y<< ' ';
        if (rgt[y] == 0) {
            //viz[x] = 1;
            lft[x] = y;         // nodul nostru nu
            rgt[y] = x;         // este cuplat sub
            return 1;           // nicio forma
        }
    }

    for (i = 0; i < l; i++) {
        y = ls[x][i];
        if (cuplu(rgt[y])) {
            //viz[x] = 1;         // nodul din dreapta este
            lft[x] = y;         // deja cuplat iar celalalt
            rgt[y] = x;         // nod din acel cuplu se
            return 1;           // poate cupla cu altceva
        }
    }
    return 0;
}

int main() {
    f >> n >> m >> e;
    while (e--) {
        f >> x >> y;
        //g<< x<<' ' << y << '\n';
        ls[x].push_back(y);
    }
    bool ok = 1;
    while (ok) {
        ok = 0;
        memset(viz, 0, sizeof(viz));
        for (i = 1; i <= n; i++)
            if (lft[i] == 0)
                ok |= cuplu(i);
    }
    for (i = 1; i <= n; i++)
        sol += (lft[i]>0);
    g << sol << '\n';
    for (i = 1; i <= n; i++)
        if (lft[i])
            g << i  << ' '<<lft[i] << '\n';
    return 0;
}