Pagini recente » Cod sursa (job #1067083) | Cod sursa (job #2432788)
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
const int NMAX = 10005;
vector<int> g[2 * NMAX];
int dist[2 * NMAX], match[2 * NMAX], n, m;
bool dfs(int u) {
for(auto v : g[u]) {
int u2 = match[v];
if(u2 == 0) {
match[u] = v;
match[v] = u;
return 1;
} else if(dist[u2] == dist[u] + 1) {
bool state = dfs(u2);
if(state == 1) {
match[u] = v;
match[v] = u;
return 1;
}
}
}
return 0;
}
void bfs() {
queue<int> q;
for(int i = 1; i <= n; i ++) {
if(match[i] == 0) {
q.push(i);
dist[i] = 0;
} else
dist[i] = -1;
}
while(q.size()) {
int u = q.front();
q.pop();
for(auto v : g[u]) {
int u2 = match[v];
if(u2 && dist[u2] == -1) {
dist[u2] = dist[u] + 1;
q.push(u2);
}
}
}
}
int hopcroftkarp() {
int ans = 0;
bool found = 1;
while(found) {
found = 0;
bfs();
for(int i = 1; i <= n; i ++) {
if(dist[i] == 0 && dfs(i) == 1) {
found = 1;
ans ++;
}
}
}
return ans;
}
int main() {
int e;
in >> n >> m >> e;
for(int i = 1; i <= e; i ++) {
int x, y;
in >> x >> y;
y += n;
g[x].push_back(y);
g[y].push_back(x);
}
out << hopcroftkarp() << "\n";
for(int i = 1; i <= n; i ++)
if(match[i])
out << i << " " << match[i] - n << "\n";
return 0;
}