Cod sursa(job #2077238)

Utilizator Horia14Horia Banciu Horia14 Data 27 noiembrie 2017 20:22:52
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include<cstdio>
#include<vector>
#define MAX_N 10000
using namespace std;

vector<int>G[MAX_N+1];
int match1[MAX_N+1], match2[MAX_N+1], n, m, e;
bool used[MAX_N+1];

int match(int node) {
    if(used[node])
        return 0;
    used[node] = true;
    for(vector<int>::iterator it = G[node].begin(); it != G[node].end(); it++) {
        if(!match2[*it]) {
            match1[node] = *it;
            match2[*it] = node;
            return 1;
        }
    }
    for(vector<int>::iterator it = G[node].begin(); it != G[node].end(); it++) {
        if(match(match2[*it])) {
            match1[node] = *it;
            match2[*it] = node;
            return 1;
        }
    }
    return 0;
}

int main() {
    int x, y, wasChanged, nrm;
    FILE *fin, *fout;
    fin = fopen("cuplaj.in","r");
    fout = fopen("cuplaj.out","w");
    fscanf(fin,"%d%d%d",&n,&m,&e);
    for(int i = 0; i < e; i++) {
        fscanf(fin,"%d%d",&x,&y);
        G[x].push_back(y);
    }
    wasChanged = 1;
    while(wasChanged) {
        wasChanged = 0;
        for(int i = 1; i <= n; i++)
            used[i] = false;
        for(int i = 1; i <= n; i++)
            if(!match1[i])
                wasChanged += match(i);
    }
    nrm = 0;
    for(int i = 1; i <= n; i++)
        if(match1[i])
            nrm++;
    fprintf(fout,"%d\n",nrm);
    for(int i = 1; i <= n; i++)
        if(match1[i])
            fprintf(fout,"%d %d\n",i,match1[i]);
    fclose(fin);
    fclose(fout);
    return 0;
}