Cod sursa(job #2961991)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 7 ianuarie 2023 16:21:22
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("cuplaj.in");
ofstream g("cuplaj.out");
#define cin f
#define cout g

int N, M, E;
int n;
vector<unordered_map<int, int>> capacity;
vector<vector<int>> adj;
unordered_map<int, int> ans;

int bfs(int s, int t, vector<int> &parent)
{
	fill(parent.begin(), parent.end(), -1);
	parent[s] = -2;

	queue<int> Q;
	Q.push(s);

	while(! Q.empty())
	{
		int cur = Q.front();
		Q.pop();

		for(int next : adj[cur])
		{
			if(parent[next] == -1 and capacity[cur][next] != 0)
			{
				parent[next] = cur;

				if(next == t)
					return 1;

				Q.push(next);
			}
		}
	}

	return 0;
}

int maxflow(int s, int t)
{
	int flow = 0, new_flow;
	vector<int> parent(n + 1);

	while(new_flow = bfs(s, t, parent))
	{
		flow += new_flow;

		int cur = t;
		while(cur != s)
		{
			int prev = parent[cur];
			capacity[cur][prev] += new_flow;
			capacity[prev][cur] -= new_flow;

			if(prev <= N)
				ans[prev] = cur;

			cur = prev;
		}
	}

	return flow;
}

int main()
{
	cin >> N >> M >> E;
	n = N + M + 2;
	capacity.resize(n + 1);
	adj.resize(n + 1);
	
	for(int i = 1; i <= E; i++)
	{
		int x, y;
		cin >> x >> y;
		adj[x].push_back(y + N);
		adj[y + N].push_back(x);
		capacity[x][y + N] = 1;
		capacity[y + N][x] = 0;
	}

	int s, t;
	s = n - 1, t = n;

	for(int i = 1; i <= N; i++)
	{

		adj[s].push_back(i);
		adj[i].push_back(s);
		capacity[s][i] = 1;
		capacity[i][s] = 0;
	}

	for(int i = 1; i <= M; i ++)
	{
		adj[i + N].push_back(t);
		adj[t].push_back(i + N);
		capacity[i + N][t] = 1;
		capacity[t][i + N] = 0;
	}

	cout<<maxflow(s, t)<<'\n';

	for(auto it : ans)
		cout<<it.first<<' '<<it.second - N<<'\n';

	return 0;
}