Pagini recente » Cod sursa (job #2256704) | Cod sursa (job #2874617) | Cod sursa (job #47887) | Cod sursa (job #1901306) | Cod sursa (job #3145286)
#include <bits/stdc++.h>
using namespace std;
class min_cost_flow{
static const int nmax = 500;
int cap[nmax][nmax], cost[nmax][nmax];
vector<vector<vector<int>>> g;
vector<vector<int>> graph;
int source, dest;
public:
min_cost_flow(int s, int d, const vector<vector<vector<int>>>& g):g(g)
{
source = s;
dest = d;
memset(cap, 0, sizeof(cap));
}
void build()
{
int n = g.size();
graph.resize(n);
for(int i = 0;i < n;++i)
{
for(int j = 0;j < g[i].size();++j)
{
int neigh = g[i][j][0];
graph[i].push_back(neigh);
graph[neigh].push_back(i);
cap[i][neigh] = g[i][j][1];
cost[i][neigh] = g[i][j][2];
cost[neigh][i] = -g[i][j][2];
}
}
}
bool bellman(int& cost_flow)
{
int d[nmax], prev[nmax];
bool in[nmax];
const int inf = 1e7;
queue<int> q;
q.push(source);
for(int i = 0;i < nmax;++i)
in[i] = false, d[i] = inf;
d[source] = 0;
in[source] = true;
while(!q.empty())
{
int nod = q.front();
q.pop();
in[nod] = false;
for(int i = 0;i < graph[nod].size();++i)
{
int neigh = graph[nod][i];
if(cap[nod][neigh] > 0 && d[nod] + cost[nod][neigh] < d[neigh])
{
d[neigh] = d[nod] + cost[nod][neigh];
prev[neigh] = nod;
if(!in[neigh])
{
q.push(neigh);
in[neigh] = true;
}
}
}
}
if(d[dest] == inf)
return false;
//Get the path back
int nod = dest, min_cap = inf;
while(nod != source)
{
int pr = prev[nod];
min_cap = min(min_cap, cap[pr][nod]);
nod = pr;
}
nod = dest;
while(nod != source)
{
int pr = prev[nod];
cap[pr][nod] -= min_cap;
cap[nod][pr] += min_cap;
nod = pr;
}
cost_flow = min_cap * d[dest];
return true;
}
int flow()
{
build();
int cost = 0, ans = 0;
while(bellman(cost))
ans += cost;
return ans;
}
};
int main() {
freopen("fmcm.in", "r", stdin);
freopen("fmcm.out", "w", stdout);
int n, m, s, d;
cin >> n >> m >> s >> d;
vector<vector<vector<int>>> g(n);
for(int i = 0;i < m;++i)
{
int a, b, cap, cost;
cin >> a >> b >> cap >> cost;
--a, --b;
g[a].push_back({b, cap, cost});
}
min_cost_flow f(s - 1, d - 1, g);
cout << f.flow();
}