Pagini recente » Cod sursa (job #2891794) | Cod sursa (job #1617791) | Cod sursa (job #763464) | Cod sursa (job #1760933) | Cod sursa (job #2402829)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int NM = 100001;
const int INF = 1 << 30;
const int NIL = 0;
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
int m, n, e;
int perechi_st[NM], perechi_dr[NM], d[NM], q[NM];
vector <int> a[NM];//vecinii fiecarui varf din stanga
bool bfs()
{
int st = 0, dr = -1, x, z;
//initializare d
for (int i = 1; i <= n; i++)
{
if (perechi_st[i] == NIL)
{
d[i] = 0;
q[++dr] = i;
}
else
{
d[i] = INF;
}
}
d[NIL] = INF;
while (st <= dr)
{
x = q[st++];
if (d[x] < d[NIL])
{
for (auto y: a[x])
{
z = perechi_dr[y];
if (d[z] == INF)
{
d[z] = 1 + d[x];
q[++dr] = z;
}
}
}
}
return (d[NIL] != INF);
}
bool dfs(int x)
{
if (x == NIL)
{
return true;
}
for (auto y: a[x])
{
int z = perechi_dr[y];
if (d[z] == 1 + d[x])
{
if (dfs(z))
{
perechi_st[x] = y;
perechi_dr[y] = x;
return true;
}
}
}
return false;
}
int main()
{
in >> n >> m >> e;
for (int i = 0; i < e; i++)
{
int x, y;
in >> x >> y;
a[x].push_back(y);
}
in.close();
for (int i = 1; i <= n; i++)
{
perechi_st[i] = NIL;
}
for (int i = 1; i <= m; i++)
{
perechi_dr[i] = NIL;
}
int cuplaj = 0;
while (bfs())
{
for (int i = 1; i <= n; i++)
{
if (perechi_st[i] == NIL && dfs(i))
{
cuplaj++;
}
}
}
out << cuplaj << "\n";
for (int i = 1; i <= n; i++)
{
if (perechi_st[i] != NIL)
{
out << i << " " << perechi_st[i] << "\n";
}
}
out.close();
return 0;
}