Cod sursa(job #1775490)

Utilizator danielNiculaeDaniel Niculae danielNiculae Data 10 octombrie 2016 14:52:10
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include "fstream"
#include "vector"
#include "cstring"

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int NMAX = 10005;
const int MMAX = 10005;

int N, M, E;
vector<int> graph[NMAX];
int coupling = 0;
int r[NMAX];
int l[MMAX];
bool used[NMAX];


bool findPath(int node) {
//    fout << "Finding path for node: " << node << "\n";

    if(used[node]) {
        return false;
    }
    used[node] = true;
    for(vector<int>::iterator it = graph[node].begin() ; it != graph[node].end() ; it++) {
        if(!l[*it]) {
            r[node] = *it;
            l[*it] = node;
            return true;
        }
    }
//    fout << "Didn't find any direct matches" << "\n";

    for(vector<int>::iterator it = graph[node].begin() ; it != graph[node].end() ; it++) {
//        fout << "Trying to redirect: " << *it << "\n";
        if(findPath(l[*it])) {
            r[node] = *it;
            l[*it] = node;
            return true;
        }
    }

    return false;
}

int main() {

    fin >> N >> M >> E;

    for(int i = 1 ; i <= E ; i++) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }

    for(bool change = true; change;) {
        change = false;
        memset(used, 0, N + 1);
        for(int i = 1 ; i <= N ; i++) {
            if(!r[i]) {
                change |= findPath(i);
            }
        }
//        fout << "Another iteration " << "\n";
    }

    for(int i = 1 ; i <= N ; i++) {
        if(r[i]) {
            coupling += 1;
        }
    }

    fout << coupling << "\n";
    for(int i = 1 ; i <= N ; i++) {
        if(r[i]) {
            fout << i << " " << r[i] << "\n";
        }
    }

    return 0;
}