Pagini recente » Cod sursa (job #2885710) | Cod sursa (job #3193380)
#include <bits/stdc++.h>
#define pragma ("O3")
#define pragma ("Ofast")
#define int short int
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
int n, m, s, t;
const int N = 350;
vector <int> g[N];
int cap[N][N], cost[N][N], dist[N], viz[N];
const int INF = 2e9;
void bellman()
{
for(int i = 1; i <= n; i++)
dist[i] = INF;
queue <int> q;
q.push(s);
dist[s] = 0;
while(q.size())
{
int cur = q.front();
q.pop();
for(auto next:g[cur])
{
if(cap[cur][next] > 0 && (dist[next] > dist[cur] + cost[cur][next]))
{
dist[next] = dist[cur] + cost[cur][next];
q.push(next);
}
}
}
}
struct cmp
{
bool operator()(pair <int, int> a, pair <int, int> b)
{
return a.first> b.first;
}
};
int dijk[N], d[N], pred[N];
bool dijkstra(int s, int t)
{
for(int i = 1; i <= n; i++)
{
dijk[i] = INF;
d[i] = INF;
viz[i] = 0;
pred[i] = 0;
}
d[s] = 0;
dijk[s] = 0;
priority_queue <pair <int, int>, vector <pair< int, int>>, cmp> pq;
pq.push({0, s});
while(pq.size())
{
int cur = pq.top().second;
pq.pop();
if(viz[cur])
continue;
viz[cur] = 1;
for(auto next:g[cur])
{
if(cap[cur][next] > 0 && d[next] > d[cur] + cost[cur][next] + dist[cur] - dist[next])
{
d[next] = d[cur] + cost[cur][next] + dist[cur] - dist[next];
dijk[next] = dijk[cur] + cost[cur][next];
pred[next] = cur;
pq.push({d[next], next});
}
}
}
return (dijk[t] != INF);
}
int32_t main()
{
in >> n >> m >> s >> t;
for(int i = 1; i <= m; i++)
{
int x, y, capacitate, c;
in >> x >> y >> capacitate >> c;
g[x].push_back(y);
g[y].push_back(x);
cap[x][y] = capacitate;
cost[x][y] = c;
cost[y][x] = -c;
}
bellman();
int max_flux_min_cost = 0;
while(dijkstra(s, t))
{
int x = t, minim = INF;
while(x != s)
{
minim = min(minim, cap[pred[x]][x]);
x = pred[x];
}
if(minim <= 0)
{
continue;
}
max_flux_min_cost += minim * dijk[t];
x = t;
while(x != s)
{
cap[pred[x]][x] -= minim;
cap[x][pred[x]] += minim;
x = pred[x];
}
for(int i = 1; i <= n; i++)
{
dist[i] = d[i];
}
}
out << max_flux_min_cost;
return 0;
}