Pagini recente » Borderou de evaluare (job #1260571) | Cod sursa (job #1194905) | Cod sursa (job #921703) | Borderou de evaluare (job #278360) | Cod sursa (job #2550105)
#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];
bool BellmanFord()
{
for(int i = 1; i <= N; i++)
costTo[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;
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())
{
int pumpFlow = capacity[bef[D]][D] - flow[bef[D]][D];
for(int i = D; i != S; i = bef[i])
pumpFlow = min(pumpFlow, capacity[bef[i]][i] - flow[bef[i]][i]);
for(int i = D; i != S; i = bef[i])
{
flow[bef[i]][i] += pumpFlow;
flow[i][bef[i]] -= pumpFlow;
}
ans += pumpFlow * costTo[D];
}
fout << ans << '\n';
return 0;
}