Pagini recente » Cod sursa (job #2394936) | Cod sursa (job #39181) | Cod sursa (job #1901891) | Cod sursa (job #548534) | Cod sursa (job #3125935)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
using ll = long long;
const int nmax = 350 , mmax = 12500;
const int inf = 1e9;
int n, m, s, d;
int add;
struct edge {
int cost;
int r , cap;
int av ()
{
return cap - r;
}
};
vector<edge> e[nmax+1][nmax+1];
pair<int , int> p[nmax+1];
bool bellman ()
{
priority_queue<pair<int , int> , vector<pair<int , int>> , greater<pair<int , int>> > q;
q.push({0 , s});
vector<int> dist(n+1 , inf);
dist[s] = 0;
while (q.size())
{
int nod = q.top().second;
int cost = q.top().first;
// cout << cost << '\n';
q.pop();
// add = dist[d];
// if (nod == d) return 1;
if (cost > dist[nod]) continue;
for (int to = 1; to <= n; to++)
{
for (int i = 0; i < e[nod][to].size(); i++)
{
edge edg = e[nod][to][i];
if (edg.r == edg.cap) continue;
if (cost + edg.cost < dist[to])
{
dist[to] = cost + edg.cost;
p[to] = {nod, i};
q.push({dist[to] , to});
}
}
}
}
add = dist[d];
if (dist[d] < inf) return 1;
else return 0;
}
int main ()
{
freopen("fmcm.in" , "r" , stdin);
freopen("fmcm.out" , "w" , stdout);
cin >> n >> m >> s >> d;
for (int i = 1; i <= m; i++)
{
int x , y , c , z;
cin >> x >> y >> c >> z;
e[x][y].push_back({z , 0 , c});
e[y][x].push_back({-z, 0 , 0});
}
int fluxTotal = 0;
ll answer = 0;
while (bellman())
{
int nod = d;
int flow = inf;
while (nod != s)
{
int ind = p[nod].second , pnod = p[nod].first;
flow = min(flow , e[pnod][nod][ind].av());
nod = pnod;
}
nod = d;
while (nod != s)
{
int ind = p[nod].second , pnod = p[nod].first;
e[pnod][nod][ind].r += flow;
nod = pnod;
}
fluxTotal += flow;
answer += 1ll * add * flow;
// cout << add << ' ' << flow << '\n';
}
cout << answer << '\n';
}