Pagini recente » Cod sursa (job #251680) | Cod sursa (job #1906640) | Cod sursa (job #1524345) | Cod sursa (job #997621) | Cod sursa (job #2831366)
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
const ll inf = 1e18 + 5;
vector <vector<int>> v, cost, cap;
vector <ll> d, old;
vector <int> tt;
bool dijkstra(int n, int s, int dest){
vector <bool> vis(n + 1);
vector <ll> newD(n + 1);
vis[s] = true;
d[s] = 0;
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;
q.push(make_pair(d[s], s));
while(!q.empty()){
int x = q.top().second, c = q.top().first;
q.pop();
if(d[x] < c)
continue;
for(auto y: v[x])
if(cap[x][y]){
int newDist = d[x] + cost[x][y] + old[x] - old[y];
if(newDist < d[y]){
d[y] = newDist;
newD[y] = newD[x] + cost[x][y];
q.push(make_pair(d[y], y));
tt[y] = x;
vis[y] = true;
}
}
}
old = newD;
return vis[dest];
}
int main()
{
int n, m, s, dest;
fin >> n >> m >> s>> dest;
cost.resize(n + 1, vector<int>(n + 1));
cap.resize(n + 1, vector<int>(n + 1));
v.resize(n + 1);
d.resize(n + 1, inf);
old.resize(n + 1);
tt.resize(n + 1, -1);
for(int i = 1; i <= m; i++){
int x, y, c, z;
fin >> x >> y >> c >>z;
cost[x][y] = z;
cost[y][x] = -z;
cap[x][y] = c;
v[x].push_back(y);
v[y].push_back(x);
}
ll flow = 0, flowCost = 0;
while(dijkstra(n, s, dest)){
ll val = inf;
for(int x = dest; x != s; x = tt[x])
val = min(val, (ll)cap[tt[x]][x]);
for(int x = dest; x != s; x = tt[x]){
cap[tt[x]][x] -= val;
cap[x][tt[x]] += val;
}
flow += val;
flowCost += val * old[dest];
fill(tt.begin(), tt.end(), -1);
fill(d.begin(), d.end(), inf);
}
fout << flowCost;
return 0;
}