Pagini recente » Cod sursa (job #1896966) | Cod sursa (job #566449) | Cod sursa (job #2972166) | Cod sursa (job #1427693) | Cod sursa (job #2238497)
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
#include <queue>
#define dMAX (1 << 9)
#define INF (1 << 19)
using namespace std;
typedef pair<int, int> pi;
int n, m, s, de;
int x, y, c, z;
int dist[dMAX], dij[dMAX], father[dMAX], oldD[dMAX];
int pVerif, newV, cost, newD;
int currentFlow, currentCost, maxFlow, maxFlowCost;
vector<int> graf[dMAX];
vector<int> tgraf[dMAX];
deque<int> d;
priority_queue<pi, vector<pi>, greater<pi> > H;
int C[dMAX][dMAX], F[dMAX][dMAX], Z[dMAX][dMAX];
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
bool Dijkstra() {
int i, j;
for (i = 1; i <= n; i++) dist[i] = INF;
dist[s] = dij[s] = 0;
H.push({0, s});
while (!H.empty()) {
int cst = H.top().first, node = H.top().second;
H.pop();
if (dist[node] != cst) continue;
vector<int> :: iterator it;
for (it = graf[node].begin(); it != graf[node].end(); it++) {
if (C[node][*it]) {
newD = dist[node] + Z[node][*it] + oldD[node] - oldD[*it];
if (newD < dist[*it]) {
dist[*it] = newD;
dij[*it] = dij[node] + Z[node][*it];
father[*it] = node;
H.push({dist[*it], *it});
}
}
}
}
for (i = 1; i <= n; i++) {
oldD[i] = dij[i];
}
if (dist[de] == INF) return false;
currentFlow = INF, currentCost = 0;
for (i = de; i != s; i = father[i]) {
currentFlow = min(currentFlow, C[father[i]][i]);
currentCost += Z[father[i]][i];
}
maxFlow += currentFlow;
maxFlowCost += currentFlow * dij[de];
for (i = de; i != s; i = father[i]) {
C[father[i]][i] -= currentFlow;
C[i][father[i]] += currentFlow;
}
return true;
}
void BellmanFord() {
int i, j;
for (i = 1; i <= n; i++) dist[i] = INF;
dist[s] = 0;
d.push_back(s);
while (!d.empty()) {
pVerif = d.front();
d.pop_front();
for (i = 0; i < tgraf[pVerif].size(); i++) {
newV = tgraf[pVerif][i];
cost = Z[pVerif][newV];
if (dist[newV] > dist[pVerif] + cost) {
dist[newV] = dist[pVerif] + cost;
d.push_back(newV);
}
}
}
/*for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (C[i][j]) {
Z[i][j] = Z[i][j] + dist[i] - dist[j];
Z[j][i] = -Z[i][j];
}
}
}*/
}
int main()
{
int i, j;
fin >> n >> m >> s >> de;
for (i = 1; i <= m; i++) {
fin >> x >> y >> c >> z;
tgraf[x].push_back(y);
graf[x].push_back(y);
graf[y].push_back(x);
C[x][y] = c;
Z[x][y] = z;
Z[y][x] = -z;
}
BellmanFord();
while (Dijkstra()) {
}
fout << maxFlowCost;
return 0;
}