Pagini recente » Cod sursa (job #195403) | Cod sursa (job #2631590) | Cod sursa (job #1713684) | Cod sursa (job #1045391) | Cod sursa (job #2958768)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
int n,m,a,b,c;
vector<int> lista_adiacenta[1024];
int cost[1024][1024];
int flux[1024][1024];
int main() {
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin >>n>>m;
for (int i = 0; i < m; ++i) {
fin >> a >> b >> c;
lista_adiacenta[a].push_back(b);
lista_adiacenta[b].push_back(a);
cost[a][b] += c;
}
int sursa = 1;
int destinatie = n;
bool gasireLant = false;
queue<int> coada;
vector<bool> viz;
vector<int> tata;
bool gasireDestinatie;
int total = 0;
do {
coada = queue<int>();
viz = vector<bool>(n + 1, false);
tata = vector<int>(n + 1, -1);
gasireDestinatie = false;
coada.push(sursa);
viz[sursa] = true;
while (!coada.empty() && !gasireDestinatie) {
int nodCurent = coada.front();
coada.pop();
if (nodCurent == destinatie) {
continue;
}
for (int j = 0; j < lista_adiacenta[nodCurent].size(); j++) {
int vecin = lista_adiacenta[nodCurent][j];
if (!viz[vecin] && cost[nodCurent][vecin] - flux[nodCurent][vecin] > 0) {
viz[vecin] = true;
coada.push(vecin);
viz[vecin] = true;
tata[vecin] = nodCurent;
}
}
if (viz[destinatie]) {
gasireDestinatie = true;
break;
}
}
if (gasireDestinatie) {
int vecin = 0;
for (int t = 0; t < lista_adiacenta[destinatie].size(); ++t) {
vecin = lista_adiacenta[destinatie][t];
if (flux[vecin][destinatie] == cost[vecin][destinatie] || !viz[vecin]) {
continue;
}
tata[destinatie] = vecin;
int cNode = destinatie;
int pNode = destinatie;
int fluxC = -1;
while (true) {
if (pNode == -1) {
break;
}
if (pNode != -1 && pNode != cNode) {
if (fluxC == -1 || cost[pNode][cNode] - flux[pNode][cNode] < fluxC) {
fluxC = cost[pNode][cNode] - flux[pNode][cNode];
}
}
cNode = pNode;
pNode = tata[pNode];
}
cNode = destinatie;
pNode = destinatie;
while (true) {
if (pNode == -1) {
break;
}
if (pNode != -1 && pNode != cNode) {
flux[pNode][cNode] += fluxC;
flux[cNode][pNode] -= fluxC;
}
cNode = pNode;
pNode = tata[pNode];
}
total += fluxC;
gasireLant = true;
}
}
else
{
gasireLant = false;
}
} while (gasireLant);
fout << total;
return 0;
}