Cod sursa(job #1474593)

Utilizator Vlad_lsc2008Lungu Vlad Vlad_lsc2008 Data 22 august 2015 13:27:17
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;

vector<vector<int>> adjl;
vector<int> match0, match1;
vector<bool> visited;

bool dfs(int u) {
    if (visited[u]) return false;
    visited[u] = true;
    for (auto v: adjl[u]) {
        if (match1[v] == -1 || dfs(match1[v])) {
            match0[u] = v;
            match1[v] = u;
            return true;
        }
    }
    return false;
}

int main() {
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);
    int n, m, e;
    cin >> n >> m >> e;
    adjl.resize(n);
    match0.assign(n, -1);
    match1.assign(m, -1);
    visited.assign(n, false);

    for (int u, v, i = 0; i < e; i++) {
        cin >> u >> v;
        adjl[u-1].push_back(v-1);
    }

    int cnt = 0;
    bool change;
    do {
        change = false;
        fill(visited.begin(), visited.end(), false);
        for (int i = 0; i < n; i++) {
            if (match0[i] == -1 && !visited[i]) {
                if (dfs(i)) {
                    ++cnt;
                    change = true;
                }
            }
        }
    } while (change);

    printf("%d\n", cnt);
    for (int i = 0; i < n; i++) {
        if (match0[i] != -1)
            printf("%d %d\n", i+1, match0[i]+1);
    }
    return 0;
}