Cod sursa(job #3001983)

Utilizator TudosieRazvanTudosie Marius-Razvan TudosieRazvan Data 14 martie 2023 10:13:48
Problema Cuplaj maxim in graf bipartit Scor 32
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <cstdio>
#include <cmath>
#include <climits>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <bitset>
#include <map>
#include <cstring>
#include <algorithm>

#define NMAX 10003

using namespace std;

FILE* fin, * fout;

int n, m,k;
int st[NMAX], dr[NMAX];
bool viz[NMAX];
int muchii;
vector<int>graf[NMAX];

bool cupleaza(int nod)
{
	if (viz[nod])
	{
		return false;
	}
	viz[nod] = true;
	for (int i = 0; i < graf[nod].size(); i++)
	{
		int nd = graf[nod][i];
		if (dr[nd] == 0)
		{
			muchii++;
			dr[nd] = nod;
			st[nod] = nd;
			return true;
		}
	}
	for (int i = 0; i < graf[nod].size(); i++)
	{
		int nd = graf[nod][i];
		if (cupleaza(nd))
		{
			dr[nd] = nod;
			st[nod] = nd;
			return true;
		}
	}
	return false;
}

int main()
{
	fin = fopen("cuplaj.in", "r");
	fout = fopen("cuplaj.out", "w");
	
	fscanf(fin, "%d %d %d", &n, &m, &k);
	for (int i = 1; i <= k; i++)
	{
		int x, y;
		fscanf(fin, "%d %d", &x, &y);
		graf[x].push_back(y);
	}

	bool ok = false;
	do {
		ok = true;
		memset(viz, 0, sizeof(viz));
		for (int i = 1; i <= n; i++)
		{
			if (st[i] == 0 && cupleaza(i) == 1)
			{
				
				ok = false;
				break;
			}
		}
	} while (!ok);

	fprintf(fout, "%d\n", muchii);
	for (int i = 1; i <= n; i++)
	{
		if (st[i] != 0)
		{
			fprintf(fout, "%d %d\n", i, st[i]);
		}
	}
	return 0;
}