Pagini recente » Cod sursa (job #1707655) | Cod sursa (job #1669269) | Cod sursa (job #745077) | Cod sursa (job #2363962) | Cod sursa (job #578707)
Cod sursa(job #578707)
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <queue>
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
const int N = 353;
const int INF = 0x3f3f3f;
int n, s, d;
int fat[N];
int best[N];
int flow[N][N];
int cost[N][N];
int capc[N][N];
void Read()
{
int m;
in >> n >> m >> s >> d;
while (m--)
{
int a, b, cap, price;
in >> a >> b >> cap >> price;
capc[a][b] = cap;
cost[a][b] = price;
cost[b][a] = -price;
}
}
bool Road()
{
queue <int> q;
memset(best, INF, sizeof(best));
q.push(s);
best[s] = 0;
while (!q.empty())
{
int node = q.front();
for (int i = 1; i <= n; ++i)
if (capc[node][i] - flow[node][i] > 0
&& best[node] + cost[node][i] < best[i])
{
best[i] = best[node] + cost[node][i];
fat[i] = node;
q.push(i);
}
q.pop();
}
return (best[d] != INF);
}
int GetMaxFlow()
{
int totalCost = 0;
while (Road())
{
int node = d;
int minFlow = INF;
while (node != s)
{
if (capc[fat[node]][node] - flow[fat[node]][node] < minFlow)
minFlow = capc[fat[node]][node] - flow[fat[node]][node];
node = fat[node];
}
node = d;
while (node != s)
{
flow[fat[node]][node] += minFlow;
flow[node][fat[node]] -= minFlow;
totalCost += minFlow * cost[fat[node]][node];
node = fat[node];
}
}
return totalCost;
}
int main()
{
Read();
out << GetMaxFlow() << "\n";
return 0;
}