Pagini recente » Cod sursa (job #984371) | Cod sursa (job #607184) | Cod sursa (job #1140243) | Cod sursa (job #787290) | Cod sursa (job #2651274)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
const int NMAX = 100005;
const int INF = 2e9 + 5;
const int NIL = 0;
vector<int>G[NMAX];
int pereche[NMAX], dist[NMAX];
int n, m, p;
int bfs()
{
queue<int>q;
dist[NIL] = INF;
for (int i = 1; i <= n; i++)
{
if (pereche[i])
dist[i] = INF;
else
{
dist[i] = 0;
q.push(i);
}
}
while (!q.empty())
{
int u = q.front();
q.pop();
if (u)
{
for (int v : G[u])
{
if (dist[pereche[v]] == INF)
{
dist[pereche[v]] = dist[u] + 1;
q.push(pereche[v]);
}
}
}
}
return (dist[NIL] != INF);
}
int dfs(int u)
{
if (u)
{
for (int v : G[u])
{
if (dist[u] + 1 == dist[pereche[v]])
if (dfs(pereche[v]))
{
pereche[v] = u;
pereche[u] = v;
return true;
}
}
dist[u] = INF;
return false;
}
return true;
}
int hopcroftKarp()
{
int nrPerechi = 0;
for (int i = 1; i <= n + m; i++)
pereche[i] = 0;
while (bfs())
{
for (int i = 1; i <= n; i++)
if (!pereche[i] && dfs(i))
nrPerechi++;
}
return nrPerechi;
}
void read()
{
int x, y;
fin >> n >> m >> p;
while (p--)
{
fin >> x >> y;
G[x].push_back(y + n);
G[y + n].push_back(x);
}
}
void solve()
{
int nrPerechi = hopcroftKarp();
fout << nrPerechi << "\n";
for (int i = 1; i <= n; i++)
if (pereche[i])
fout << i << " " << pereche[i] - n << "\n";
}
int main()
{
read();
solve();
return 0;
}