Cod sursa(job #1867450)

Utilizator andru47Stefanescu Andru andru47 Data 4 februarie 2017 09:18:54
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 10000 + 5;
int n,m,muchii,cuplat1[NMAX],cuplat2[NMAX];
bool ok[NMAX];
vector <int> g[NMAX];
inline bool cupleaza(int nod) {
    if(ok[nod] == true)
        return false;
    ok[nod] = true;
    for (auto &it : g[nod])
        if (!cuplat2[it]) {
            cuplat1[nod] = it;
            cuplat2[it] = nod;
            return true;
        }
    for (auto &it : g[nod])
        if (cupleaza(cuplat2[it]) == true) {
            cuplat1[nod] = it;
            cuplat2[it] = nod;
            return true;
        }
    return false;
}
int main() {
    freopen("cuplaj.in","r",stdin);
    freopen("cuplaj.out","w",stdout);
    scanf("%d %d %d\n", &n, &m, &muchii);
    for (int i = 1; i<=muchii; ++i) {
        int x, y;
        scanf("%d %d\n", &x, &y);
        g[x].push_back(y);
    }
    bool last = true;
    while(last) {
        last = false;
        memset(ok,false,sizeof(ok));
        for (int i = 1; i<=n; ++i)
            if (cuplat1[i] == false)
                last |= cupleaza(i);
    }
    int sol = 0;
    for (int i = 1; i<=n; ++i)
        if (cuplat1[i])
            ++sol;
    printf("%d\n", sol);
    for (int i = 1; i<=n; ++i)
        if (cuplat1[i])
            printf("%d %d\n",i,cuplat1[i]);
    return 0;
}