Cod sursa(job #3327850)

Utilizator DalvDalvGhita Vladut DalvDalv Data 5 decembrie 2025 15:04:06
Problema Cuplaj maxim in graf bipartit Scor 8
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <queue>
#include <stack>
using namespace std;

const int NMAX = 1000;
const int NEXTRA = 2;
int flux[NMAX + NEXTRA + 1][NMAX + NEXTRA + 1];
int capacitate[NMAX + NEXTRA + 1][NMAX + NEXTRA + 1];
int n;

bool vis[NMAX + NEXTRA + 1];

int p[NMAX + NEXTRA + 1];

vector<int> G[NMAX + NEXTRA + 1];

int bfs(int s, int d) {
	queue<int> q;
	for(int i = 0; i <= n; i++) {
		vis[i] = 0;
		p[i] = 0;
	}

	q.push(s);
	vis[s] = 1;
	while(!q.empty()) {
		int x = q.front();
		q.pop();

		for(auto y : G[x]) {
			if(vis[y] || capacitate[x][y] - flux[x][y] <= 0) continue;

			vis[y] = 1;
			p[y] = x;
			q.push(y);

			if(y == d) break;
		}
	}

	if(vis[d] == 0) {
		return 0;
	}

	vector<int> path;
	int x = d;
	while(x != 0) {
		path.push_back(x);
		x = p[x];
	}
	reverse(path.begin(), path.end());
	int mn = 1e9;
	for(int i = 0; i < path.size() - 1; i++) {
		int x = path[i];
		int y = path[i + 1];
		mn = min(mn, capacitate[x][y] - flux[x][y]);
	}
	for(int i = 0; i < path.size() - 1; i++) {
		int x = path[i];
		int y = path[i + 1];
		flux[x][y] += mn;
		flux[y][x] -= mn;
	}

	return mn;
}

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

	int cL, cR, e;
	cin >> cL >> cR >> e;

	n = cL + cR + 2;

	for(int i = 1; i <= cL; i++) {
		int x = i + 1;
		capacitate[1][x] = 1;
		G[1].push_back(x);
		G[x].push_back(1);
	}

	for(int i = 1; i <= cR; i++) {
		int x = i + cL + 1;
		capacitate[x][n] = 1;
		G[n].push_back(x);
		G[x].push_back(n);
	}

	for(int i = 1; i <= e; i++) {
		int x, y;
		cin >> x >> y;
		x += 1;
		y += 2 + cL;

		capacitate[x][y] = 1;
		G[x].push_back(y);
		G[y].push_back(x);
	}

	int sum = 0;
	while(true) {
		int flux = bfs(1, n);
		sum += flux;

		if(flux == 0) {
			break;
		}
	}

	cout << sum << endl;

	for(int i = 2; i <= cL + 1; i++) {
		for(auto x : G[i]) {
			if(flux[i][x] <= 0) continue;
			cout << i - 1 << " " << x - cL - 2 << endl;
		}
	}
}