Cod sursa(job #1974163)

Utilizator ctrlNBDorel Andrescu ctrlNB Data 26 aprilie 2017 23:46:56
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include<bits/stdc++.h>

#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define fi first
#define se second
#define sz size
#define pb push_back
#define mp make_pair
#define bg begin
#define nd end
using namespace std;

const int maxn = 100003;

const int maxk = 100003;


class BipartiteMatcher {

private:
	vector<int> g[maxk];
	vector<int> lft, rght, viz;

	void refresh(){
		fill(viz.begin(), viz.end(), 0);
	}
public:
	BipartiteMatcher(int n, int m) : viz(n+1), lft(n+1, -1), rght(m+1, -1)  {}

	void addEdge(int a, int b) {
		g[a].push_back(b);
	}


	int match() {
		bool ok = false;
		while(ok) {
			ok = false;

			refresh();
			
			for(int i = 1; i < lft.size(); ++i)
				if(lft[i] == -1)
					ok |= pairup(i);
		}
		
		int ans = 0;
		for(int i = 1; i < lft.size(); ++i){
			ans += (lft[i] != -1 ? 1 : 0);
		}
		return ans;
	}

	bool pairup(int node) {
		if(viz[node]) 
			return false;
		viz[node] = true;
	
		for(int rightNode : g[node]) {
			if(rght[rightNode] == -1 || pairup(rght[rightNode])) {
				lft[node] = rightNode;
				rght[rightNode] = node;
				return true;
			}
		}
		return false;
	}

	vector<int> exportRight(){
		return rght;
	}
};

int main(){

	// #ifndef ONLINE_JUDGE
	freopen("cuplaj.in","r",stdin);
	freopen("cuplaj.out","w",stdout);
	// #endif

	ios_base::sync_with_stdio(false);

	int n,m,e;
	int x,y;
	cin >> n >> m >> e;
	BipartiteMatcher bm(n,m);
	for(int i=0;i<e;i++){
		cin >> x >> y;
		bm.addEdge(x,y);
	}
	bm.match();
	vector<int> res = bm.exportRight();
	for(int i=1;i<=m;i++){
		if(res[i]){
			cout << res[i] << ' ' << i << '\n';
		}
	}

	return 0;
}