Pagini recente » Cod sursa (job #1691217) | Cod sursa (job #1256736) | Cod sursa (job #3274830) | Cod sursa (job #2410613) | Cod sursa (job #2957700)
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <utility>
#include <queue>
class Flux
{
private:
int _n;
std::vector<std::vector<int>> _adiac;
std::vector<std::vector<int>> _capaci;
public:
std::vector<std::vector<int>> getCapacity() const { return _capaci; }
int getMaxFlux()
{
int total = 0;
while (1)
{
int fluxTotal = 0;
std::queue<int> q;
std::vector<int> generator(_adiac.size(), 0);
std::vector<bool> mark(_adiac.size(), 0);
q.push(0);
mark[0] = true;
while (!q.empty())
{
int nod = q.front();
q.pop();
if (nod == this->_n) // aici o sa vedem din toate caile formate daca putem adauga flux ca sa nu refacem bfs-ul iar si iar;
{
for (auto &&contestant : this->_adiac[nod])
{
if (this->_capaci[contestant][nod] == 0 or mark[contestant] == 0)
continue;
int fluxx = this->_capaci[contestant][nod];
int checkFlux = contestant;
while (checkFlux != 0)
{
fluxx = std::min(fluxx, this->_capaci[generator[checkFlux]][checkFlux]);
checkFlux = generator[checkFlux];
}
fluxTotal += fluxx;
this->_capaci[nod][contestant] += fluxx;
this->_capaci[contestant][nod] -= fluxx;
checkFlux = contestant;
while (checkFlux != 0)
{
this->_capaci[checkFlux][generator[checkFlux]] += fluxx;
this->_capaci[generator[checkFlux]][checkFlux] -= fluxx;
checkFlux = generator[checkFlux];
}
}
break;
}
for (auto &&vecin : this->_adiac[nod])
{
if (this->_capaci[nod][vecin] != 0 and mark[vecin] == 0)
{
mark[vecin] = 1;
generator[vecin] = nod;
q.push(vecin);
}
}
}
if (fluxTotal == 0)
{
break;
}
total += fluxTotal;
}
return total;
}
Flux(const std::vector<std::vector<int>> &, std::vector<std::vector<int>>, const int &);
~Flux() = default;
};
Flux::Flux(const std::vector<std::vector<int>> &v, std::vector<std::vector<int>> cap, const int &n) : _n{n}, _adiac{std::move(v)}, _capaci{std::move(cap)} {}
int main()
{
std::ifstream cin("cuplaj.in");
std::ofstream cout("cuplaj.out");
short n, m;
int x, y, e;
cin >> n >> m >> e;
const int magic = n + m + 2;
std::vector<std::vector<int>> v(magic);
std::vector<std::vector<int>> capaci(magic, std::vector<int>(magic, 0));
for (size_t i = 1; i <= n; i++)
{
v[0].push_back(i);
v[i].push_back(0);
capaci[0][i] = 1;
}
for (size_t i = 1; i <= m; i++)
{
v[m + n + 1].push_back(n + i);
v[n + i].push_back(n + m + 1);
capaci[n + i][m + n + 1] = 1;
}
for (size_t j = 0; j < e; j++)
{
cin >> x >> y;
v[x].push_back(y + n);
v[y + n].push_back(x);
capaci[x][n + y] = 1;
}
Flux asd{v, capaci, n + m + 1};
cout << asd.getMaxFlux() << '\n';
capaci = asd.getCapacity();
for (size_t i = 1; i <= n; i++)
for (auto &&mergem : v[i])
{
if (capaci[i][mergem] == 0 and mergem != 0) // daca capacitatea ramasa e 0 si j nu e nodul de start ->
{
cout << i << ' ' << mergem - n << "\n";
}
}
}