Cod sursa(job #3154389)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 4 octombrie 2023 16:15:11
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

int n, m, e;

vector<int> Pair, dist;
vector<vector<int>> g;

bool bfs() {
	queue<int> q;
	for(int i = 1; i <= n; i++) {
		if(!Pair[i]) {
			q.push(i);
			dist[i] = 0;
		} else {
			dist[i] = INT_MAX;
		}
	}
	dist[0] = INT_MAX;

	while(!q.empty()) {
		int node = q.front();
		q.pop();
		if(dist[node] < dist[0]) {
			for(auto son : g[node]) {
				if(dist[Pair[son]] == INT_MAX) { 
					dist[Pair[son]] = dist[node] + 1; 
					q.push(Pair[son]);
				}
			}
		}
	}
	return dist[0] != INT_MAX;
}

bool dfs(int node) {
	if(!node) return 1;
	for(auto son : g[node]) {
		if(dist[Pair[son]] == dist[node] + 1) {
			if(dfs(Pair[son])) {
				Pair[son] = node;
				Pair[node] = son;
				return 1;
			}
		}
	}
	dist[node] = INT_MAX;
	return 0;
}

int main() {
	scanf("%d %d %d", &n, &m, &e);

	dist.resize(n+1);
	Pair.resize(n+m+1);
	g.resize(n+m+1);

	for(int i = 0; i < e; i++) {
		int x, y;
		scanf("%d %d", &x, &y);
		y += n;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	
	int match = 0;
	while(bfs()) {
		for(int node = 1; node <= n; node++) {
			if(!Pair[node] && dfs(node)) { match++; } 
		}
	}

	printf("%d\n", match);

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