Cod sursa(job #1810286)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 19 noiembrie 2016 20:51:11
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 10000 + 1;

vector<int> G[MAX_N];
int matched[2 * MAX_N];
bool used[2 * MAX_N];

int N, M, E;

bool pairUp(int node){
    if (used[node])
        return false;

    used[node] = true;

    for (int son : G[node])
        if (!matched[son]){
            matched[son] = node;
            matched[node] = son;
            return true;
        }

    for (int son : G[node]){
        if (pairUp(matched[son])){
            matched[son] = node;
            matched[node] = son;
            return true;
        }
    }

    return false;
}

void matching(ostream &out){
    bool changed;

    do{
        changed = false;
        memset(used, 0, sizeof(used));

        for (int i = 1; i <= N; i++)
            if (!matched[i]){
                changed |= pairUp(i);
            }

    } while (changed);

    int cuplaj = 0;

    for (int i = 1; i <= N; i++){
        cuplaj += matched[i] > 0;
    }

    out << cuplaj << "\n";

    for (int i = 1; i <= N; i++){
        if (matched[i] > 0)
            out << i << " " << matched[i] - N << "\n";
    }
}

int main()
{
    ifstream in("cuplaj.in");
    ofstream out("cuplaj.out");

    in >> N >> M >> E;

    for (int i = 1; i <= E; i++){
        int u, v;
        in >> u >> v;

        G[u].push_back(v + N);
    }

    matching(out);

    return 0;
}