Pagini recente » Cod sursa (job #2491875) | Cod sursa (job #549383) | Cod sursa (job #367154) | Cod sursa (job #2400126) | Cod sursa (job #2961261)
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("cuplaj.in");
ofstream g("cuplaj.out");
int n, m, e;
vector<int> la[1001];
queue<int> q;
vector<int> st, dr, dist;
bool BFS()
{
for (int i = 1; i <= n; i++)
if (!dr[i])
{
q.push(i);
dist[i] = 0;
}
else
dist[i] = 999999;
dist[0] = 999999;
//q = nodurile din parte stanga
while (!q.empty())
{
int nod = q.front();
q.pop();
if (dist[nod] < dist[0])
{
for (int i=0;i<la[nod].size();i++)
{
int urm=la[nod][i];
if (dist[st[urm]] == 999999)
{
dist[st[urm]] = 1 + dist[nod];
q.push(st[urm]);
}
}
}
}
return dist[0] != 999999;
}
bool DFS(int nod)
{
if (nod != 0)
{
for (int i=0;i<la[nod].size();i++){
int urm=la[nod][i];
if (1 + dist[nod] == dist[st[urm]] && DFS(st[urm]))
{
st[urm] = nod;
dr[nod] = urm;
return true;
}}
dist[nod] = 999999;
return false;
}
return true;
}
int cuplajMax()
{
int rez = 0;
while (BFS())
{
for (int i = 1; i <= n; i++)
if (!dr[i] && DFS(i))
rez++;
}
return rez;
}
int main()
{
f >> n >> m >> e;
st.resize(n + 1, 0);
dr.resize(n + 1, 0);
dist.resize(n + 1, 0);
for (int i = 1; i <= e; i++)
{
int n1, n2;
f >> n1 >> n2;
la[n1].push_back(n2);
}
g << cuplajMax() << '\n';
for (int i = 1; i <= m; i++)
if (st[i])
g << st[i] << ' ' << i << '\n';
return 0;
}