Cod sursa(job #473769)

Utilizator darrenRares Buhai darren Data 31 iulie 2010 20:44:13
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <algorithm>
#include <list>

using namespace std;

#define left 0
#define right 1

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

void Read();
void Solve();
bool Match(int i);
void Write();

int n, m, e;
list<int> v[10001];
int w_match[2][10001];
bool sel[10001];
int max_match;

int main()
{
    Read();
    Solve();
    Write();
}

void Read()
{
    fin >> n >> m >> e;
    for (int i = 1, nod1, nod2; i <= e; ++i)
    {
        fin >> nod1 >> nod2;
        v[nod1].push_back(nod2);
    }
}

void Solve()
{
    //for (int i = 1; i <= max(n, m); ++i)
    //    w_match[left][i] = w_match[right][i] = -1;
    for (int i = 1; i <= n; ++i)
        if (w_match[left][i] == 0)
        {
			for (int j = 1; j <= n; ++j) sel[j] = 0;
            max_match += Match(i);
        }
}

bool Match(int i)
{
	if (sel[i] == true) return false;
	sel[i] = true;

    for (list<int>::iterator it = v[i].begin(); it != v[i].end(); ++it)
    {
        if (w_match[right][*it] == 0 || Match(w_match[right][*it]))
        {
			w_match[left][i] = *it;
			w_match[right][*it] = i;
			return true;
        }
    }
    return false;
}

void Write()
{
    fout << max_match << '\n';
    for (int i = 1; i <= n; ++i)
		if (w_match[left][i] != 0)
			fout << i << ' ' << w_match[left][i] << '\n';
}