Pagini recente » Cod sursa (job #3039182) | Cod sursa (job #414006) | Cod sursa (job #2092751) | Cod sursa (job #3241165) | Cod sursa (job #2550106)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
const int NMAX = 350;
const int INF = 20000000;
int N, M, S, D;
vector <int> g[NMAX + 5];
int capacity[NMAX + 5][NMAX + 5], flow[NMAX + 5][NMAX + 5];
int cost[NMAX + 5][NMAX + 5];
bool seen[NMAX + 5];
int costTo[NMAX + 5], bef[NMAX + 5], pumpFlow[NMAX + 5];
bool BellmanFord()
{
for(int i = 1; i <= N; i++)
costTo[i] = INF, pumpFlow[i] = INF;
queue <int> Q;
Q.push(S);
costTo[S] = 0;
seen[S] = 1;
while(!Q.empty())
{
int node = Q.front();
Q.pop();
seen[node] = 0;
for(auto it : g[node])
if(flow[node][it] < capacity[node][it])
if(costTo[it] > costTo[node] + cost[node][it])
{
costTo[it] = costTo[node] + cost[node][it];
bef[it] = node;
pumpFlow[it] = min(pumpFlow[node], capacity[node][it] - flow[node][it]);
if(seen[it] == 0)
{
seen[it] = 1;
Q.push(it);
}
}
}
return costTo[D] != INF;
}
int main()
{
fin >> N >> M >> S >> D;
for(int i = 1; i <= M; i++)
{
int x, y, cap, cst;
fin >> x >> y >> cap >> cst;
g[x].push_back(y);
g[y].push_back(x);
capacity[x][y] = cap;
cost[x][y] = cst;
cost[y][x] = -cst;
}
int ans = 0;
while(BellmanFord())
{
for(int i = D; i != S; i = bef[i])
{
flow[bef[i]][i] += pumpFlow[D];
flow[i][bef[i]] -= pumpFlow[D];
}
ans += pumpFlow[D] * costTo[D];
}
fout << ans << '\n';
return 0;
}