Cod sursa(job #2146686)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 28 februarie 2018 09:52:05
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

const int nmax = 10005;
int n, m, t, x, y, i;
bool viz[nmax];
int lft[nmax], rgt[nmax];
vector <int> ls[nmax];

bool pairup(int x) {
    if (viz[x]) return 0;
    int l = ls[x].size(), i, y;
    viz[x] = 1;
    for (i = 0; i < l; i++) {
        y = ls[x][i];
        if (rgt[y] == 0) {
            lft[x] = y;
            rgt[y] = x;
            return 1;
        }
    }

    for (i = 0; i < l; i++) {
        y = ls[x][i];
        if (pairup(rgt[y])) {
            lft[x] = y;
            rgt[y] = x;
            return 1;
        }
    }
    return 0;
}

int main() {
    f >> n >> m >> t;
    while (t--) {
        f >> x >> y;
        ls[x].push_back(y);
    }
    int ok = 1;
    while (ok) {
        ok = 0;
        memset(viz, 0, sizeof(viz));
        for (i = 1; i <= n; i++)
            if (lft[i] == 0)
                ok |= pairup(i);
    }

    int sol = 0;
    for (i = 1; i <= n; i++)
        if (lft[i])
            sol++;
    g << sol << '\n';
    for (i = 1; i <= n; i++)
        if (lft[i])
            g << i << ' ' << lft[i] << '\n';
    return 0;
}