Pagini recente » Cod sursa (job #1052552) | Cod sursa (job #323844) | Cod sursa (job #2435092) | Cod sursa (job #2928538) | Cod sursa (job #2987551)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
const int NMAX = 350, INF = 0x3f3f3f3f;
vector<int> graf[NMAX + 5];
queue<int> coada;
int N, M, capacitate[NMAX + 5][NMAX + 5], flow[NMAX + 5][NMAX + 5], tata_de[NMAX + 5], cost[NMAX + 5][NMAX + 5], dist[NMAX + 5];
int startNod, endNod;
bool in_coada[NMAX + 5];
// Implementare Bellman-Ford optimizat cu coada a.k.a SPFA
bool bellmanFord()
{
memset(tata_de, 0, sizeof tata_de);
memset(dist, INF, sizeof dist);
memset(in_coada, 0, sizeof in_coada);
coada.push(startNod);
dist[startNod] = 0;
in_coada[startNod] = true;
while (!coada.empty())
{
int nod_curent = coada.front();
coada.pop();
in_coada[nod_curent] = false;
for (int i = 0; i < graf[nod_curent].size(); i++)
{
int vecin = graf[nod_curent][i];
if (capacitate[nod_curent][vecin] - flow[nod_curent][vecin] > 0 && dist[vecin] > dist[nod_curent] + cost[nod_curent][vecin])
{
dist[vecin] = dist[nod_curent] + cost[nod_curent][vecin];
tata_de[vecin] = nod_curent;
if (!in_coada[vecin])
{
in_coada[vecin] = true;
coada.push(vecin);
}
}
}
}
return dist[endNod] != INF;
}
int main()
{
fin >> N >> M >> startNod >> endNod;
for (int i = 0; i < M; i++)
{
int from, to, capacity, cost_muchie;
fin >> from >> to >> capacity >> cost_muchie;
graf[from].push_back(to);
graf[to].push_back(from);
capacitate[from][to] = capacity;
cost[from][to] = cost_muchie;
// Ca sa ne intoarcem ca si cum nu am fi fost prin nod
cost[to][from] = -cost_muchie;
}
int max_flow = 0;
while (bellmanFord())
{
int fluxMin = INT32_MAX;
int nod = endNod;
while (nod != startNod)
{
fluxMin = min(fluxMin, capacitate[tata_de[nod]][nod] - flow[tata_de[nod]][nod]);
nod = tata_de[nod];
}
nod = endNod;
while (nod != startNod)
{
flow[tata_de[nod]][nod] += fluxMin;
flow[nod][tata_de[nod]] -= fluxMin;
nod = tata_de[nod];
}
max_flow += fluxMin * dist[endNod];
}
fout << max_flow << "\n";
return 0;
}