Cod sursa(job #2224772)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 25 iulie 2018 00:30:08
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

bool match(const vector<vector<int>>& graph, int node, vector<bool>& used,
           vector<int>& matched){
    if (used[node])
        return false;

    used[node] = true;

    for (int x: graph[node]){
        if (matched[x] == -1){
            matched[node] = x;
            matched[x] = node;
            return true;
        }
    }

    for (int x: graph[node]){
        if (match(graph, matched[x], used, matched)){
            matched[node] = x;
            matched[x] = node;
            return true;
        }
    }

    return false;
}

int main() {
//    ifstream cin("data.txt");
    ifstream cin("cuplaj.in");
    ofstream cout("cuplaj.out");

    ios_base::sync_with_stdio(false);

    int N, M, E;
    cin >> N >> M >> E;

    vector<vector<int>> graph(N);
    vector<bool> used(N + M, false);
    vector<int> matched(N + M, -1);

    for (int i = 0; i < E; i++){
        int x, y;
        cin >> x >> y;
        x--; y--;
        graph[x].push_back(y + N);
    }

    bool changed;

    do{
        changed = false;
        fill(used.begin(), used.end(), false);

        for (int i = 0; i < N; i++)
            if (matched[i] == -1)
                changed |= match(graph, i, used, matched);

    } while (changed);

    int matching = 0;

    for (int i = 0; i < N; i++)
        if (matched[i] != -1)
            matching++;

    cout << matching << "\n";

    for (int i = 0; i < N; i++)
        if (matched[i] != -1)
            cout << i + 1 << " " << matched[i] - N + 1 << "\n";

    return 0;
}