Pagini recente » Cod sursa (job #1483826) | Cod sursa (job #2987122)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
vector<int> graf[1005];
queue<int> coada;
int N, M, capacitate[1005][1005], flux[1005][1005], tata_de[1005];
bool BFS()
{
memset(tata_de, 0, sizeof tata_de);
// Introducem nodul de start
coada.push(1);
tata_de[1] = 1;
while (!coada.empty())
{
int curent = coada.front();
// Exista drum cu capacitate > 0 pana la N
coada.pop();
// Am gasit un traseu pana la nodul final
if (curent == N)
{
while (!coada.empty())
coada.pop();
return true;
}
for (int i = 0; i < graf[curent].size(); i++)
{
int vecin = graf[curent][i];
// Vecin nevizitat si mai putem transporta apa prin conducta
if (tata_de[vecin] == 0 && capacitate[curent][vecin] > flux[curent][vecin])
{
tata_de[vecin] = curent;
coada.push(vecin);
}
}
}
return false;
}
// Algoritmul Edmonds-Karp
int main()
{
fin >> N >> M;
for (int i = 0; i < M; i++)
{
int x, y, c;
fin >> x >> y >> c;
graf[x].push_back(y);
graf[y].push_back(x);
capacitate[x][y] = c;
}
int ans = 0;
// Cat timp se poate ajunge cu apa pana la nodul final
while (BFS())
{
int fluxMin = INT32_MAX;
int nod = N;
// Obtinem fluxul minim pe care il putem pompa prin conducte
while (nod != 1)
{
fluxMin = min(fluxMin, capacitate[tata_de[nod]][nod] - flux[tata_de[nod]][nod]);
nod = tata_de[nod];
}
nod = N;
// Ajustam fluxurile folosindu-ne de fluxul minim determinat pe traseu
while (nod != 1)
{
flux[nod][tata_de[nod]] -= fluxMin;
flux[tata_de[nod]][nod] += fluxMin;
nod = tata_de[nod];
}
ans += fluxMin;
}
fout << ans << "\n";
return 0;
}