Pagini recente » Cod sursa (job #2659713) | Cod sursa (job #2166702) | Profil Tudor_B. | Cod sursa (job #416193) | Cod sursa (job #2001605)
#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
int const nmax = 10000;
int n, m, e;
int dist[1 + 2 * nmax];
bool vis[1 + 2 * nmax];
vector<int> g[1 + 2 * nmax];
int match[1 + 2 * nmax];
void addedge(int x, int y) {
g[x].push_back(y);
g[y].push_back(x);
}
void bfs() {
fill(dist + 1, dist + n + m + 1, -1);
queue < int > q;
for(int i = 1; i <= n; i++){
if(match[i] <= 0){
q.push(i);
dist[i] = 0;
}
}
//u, u1, u2, noduri din stanga si v, v1, v2 noduri din dreapta
while(!q.empty()){
int u1 = q.front();
q.pop();
for(int i = 0; i < g[u1].size(); i++) {
int v1 = g[u1][i];
int u2 = match[v1]; //prin matching
if(0 < u2 && dist[u2] < 0) {
dist[u2] = dist[u1] + 1;
q.push(u2);
}
}
}
}
bool dfs(int u1) {
vis[u1] = 1;
for(int i = 0; i < g[u1].size(); i++) {
int v1 = g[u1][i];
int u2 = match[v1];
if(match[v1] <= 0) {
match[u1] = v1;
match[v1] = u1;
return true;
} else if(vis[u2] == 0 && dist[u2] == dist[u1] + 1) {
if(dfs(u2) == 1) {
match[u1] = v1;
match[v1] = u1;
return true;
}
}
}
return false;
}
int maxmatching() {
int answer = 0, add = 1;
while(0 < add) {
bfs();
fill(vis + 1, vis + n + m + 1, false);
add = 0;
for(int i = 1; i <= n; i++) {
if(match[i] <= 0){
if(dfs(i) == true)
add++;
}
}
answer += add;
}
return answer;
}
int main() {
in >> n >> m >> e;
for(int i = 1; i <= e; i++){
int x, y;
in >> x >> y;
addedge(x, y + n);
}
out << maxmatching() << '\n';
for(int i = 1; i <= n; i++){
if(0 < match[i]){
out << i << ' ' << match[i] - n << '\n';
}
}
in.close();
out.close();
return 0;
}