Cod sursa(job #1953599)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 4 aprilie 2017 21:47:59
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 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, k, i, x, y;
vector<int>ls[nmax];
int lft[nmax], rgt[nmax];
bool viz[nmax];

bool cuplu(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 (rgt[y] && cuplu(rgt[y])) {
            lft[x] = y;
            rgt[y] = x;
            return 1;
        }
    }

    return 0;
}

int main() {
    f >> n >> m >> k;
    for (i = 1; i <= k; i++) {
        f >> x >> y;
        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);
    }
    int sol = 0;
    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;

}