Pagini recente » Cod sursa (job #2113144) | Cod sursa (job #2240531) | Cod sursa (job #2625914) | Cod sursa (job #408928) | Cod sursa (job #1971345)
#include <fstream>
#include <vector>
#include <queue>
//11:40 47 58
using namespace std;
const int NMAX = 350 + 5;
const int MMAX = 12500 + 5;
const int INF = 1E9;
int N, M, S, T;
int cap[NMAX][NMAX];
int cost[NMAX][NMAX];
vector <int> graph[NMAX];
bool inQueue[NMAX];
queue <int> q;
int dist[NMAX];
int father[NMAX];
bool BF() {
for (int i = 1; i <= N; ++ i)
dist[i] = INF, father[i] = inQueue[i] = 0;
q.push(S);
dist[S] = 0;
inQueue[S] = true;
while (!q.empty()) {
int node = q.front();
q.pop();
inQueue[node] = false;
for (auto it: graph[node])
if (cap[node][it] && dist[node] + cost[node][it] < dist[it]) {
dist[it] = dist[node] + cost[node][it];
father[it] = node;
if (!inQueue[it]) {
inQueue[it] = true;
q.push(it);
}
}
}
return father[T];
}
int minCostFlow() {
int ans = 0;
while (BF()) {
int node = T;
int f = INF;
while (node != S) {
f = min(f, cap[father[node]][node]);
node = father[node];
}
node = T;
while (node != S) {
cap[father[node]][node] -= f;
cap[node][father[node]] += f;
ans += cost[father[node]][node] * f;
node = father[node];
}
}
return ans;
}
int main()
{
ifstream cin("fmcm.in");
ofstream cout("fmcm.out");
cin >> N >> M >> S >> T;
for (int i = 1; i <= M; ++ i) {
int a, b, c, d;
cin >> a >> b >> c >> d;
cap[a][b] += c;
cost[a][b] += d;
cost[b][a] -= d;
graph[a].push_back(b);
graph[b].push_back(a);
}
cout << minCostFlow() << '\n';
return 0;
}