Cod sursa(job #2962076)

Utilizator Cosmin3105Cosmin Colceru Cosmin3105 Data 7 ianuarie 2023 18:40:18
Problema Cuplaj maxim in graf bipartit Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

struct muchie {
	int x, y, c, poz;
};

vector<muchie> muchii;

int n, m, e, stg, dr, N;

vector<bool> vizitat;
vector<int> tata;
vector<vector<int>> mi;

int bfs() {
	tata.clear();
	tata.resize(n);
	fill(vizitat.begin(), vizitat.end(), 0);

	queue<int> coada;
	vizitat[stg] = true;
	coada.push(stg);

	while (!coada.empty()) {
		int nod = coada.front();
		coada.pop();

		for (auto x : mi[nod]) {
			muchie mc = muchii[x];

			if (!vizitat[mc.y] && mc.c > 0) {
				coada.push(mc.y);
				vizitat[mc.y] = true;
				tata[mc.y] = x;

				if (mc.y == dr)
					return 1;
			}

			
		}
	}
	return 0;
}

int main() {
	fin >> n >> m >> e;

	N = n + m + 2;
	stg = 0;
	dr = n - 1;

	vizitat.resize(N);
    tata.resize(N);
    mi.resize(N);
	
	int d = 0;
	for (int i = 1; i <= e; i++) {
		d += 2;
		int x, y;
		fin >> x >> y;
		mi[x].push_back(d - 2);
		mi[y + n].push_back(d - 1);
		muchii.push_back({x, y + n, 1, d - 1});
		muchii.push_back({y + n, x, 0, d - 2});
	}
	
	//int d = int(muchii.size());
	for (int i = 1; i <= n; i++) {
		d += 2;
		muchii.push_back({stg, i, 1, d - 1});
		muchii.push_back({i, stg, 0, d - 2});
		mi[stg].push_back(d - 2);
		mi[i].push_back(d - 1);
	}

	for (int i = 1 + n; i <= n + m; i++) {
		d += 2;
		muchii.push_back({i, dr, 1, d - 1});
		muchii.push_back({dr, i, 0, d - 2});
		mi[i].push_back(d - 2);
		mi[dr].push_back(d - 1);
	}

	int cmax = 0;
	while (bfs()) {
		for (auto x : mi[dr]) {
			if (vizitat[muchii[x].y] && muchii[muchii[x].poz].c != 0) {
				int minim = INT32_MAX;
				muchie mc = muchii[x];
				tata[dr] = mc.poz;
				int nod = dr;

				while (nod != stg) {
					minim = min(minim, muchii[tata[nod]].c);
					nod = muchii[tata[nod]].x;
				}

				cmax += minim;
				
				nod = dr;
				while (nod != stg) {
					muchii[tata[nod]].c -= minim;
					muchii[muchii[tata[nod]].poz].c += minim;
					nod = muchii[tata[nod]].x;
				}
			}
		}
	}
	
	fout << cmax - 1 << endl;
	for (auto x : muchii) {
		if (x.c == 0 && x.x != stg && x.y != dr && x.x < x.y) {
			fout << x.x << " " << x.y - n << endl;
		}
	}
}