#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#define SF scanf
#define PF printf
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 500;
const int MAXM = 500 * 500 / 2;
struct Node {
int u, v, c, f, cost;
};
template <int maxn, int maxm>
struct MCMF {
int n, m, s, t;
vector <Node> Edge;
vector <int> G[maxn+10];
int inq[maxn+10], d[maxn+10], p[maxn+10], a[maxn+10];
void init(int n) {
this->n = n;
for(int i = 0; i < n; i++) G[i].clear();
Edge.clear();
}
void add(int u, int v, int c, int cost) {
Edge.push_back((Node) { u, v, c, 0, cost } );
Edge.push_back((Node) { v, u, 0, 0, -cost } );
m = Edge.size();
G[u].push_back(m-2); G[v].push_back(m-1);
}
bool SPFA(int s, int t, int &Flow, int &Cost)
{
memset(d, 0x3f, sizeof(d));
memset(inq, 0, sizeof(inq));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue <int> q;
q.push(s);
while(!q.empty())
{
int u = q.front(); q.pop();
inq[u] = 0;
for(int i = 0; i < G[u].size(); i++)
{
int v = Edge[G[u][i]].v, c = Edge[G[u][i]].c, f = Edge[G[u][i]].f, cost = Edge[G[u][i]].cost;
if(c > f && d[v] > d[u] + cost) {
d[v] = d[u] + cost;
p[v] = G[u][i];
a[v] = min(a[u], c - f);
if(!inq[v]) { q.push(v); inq[v] = true; }
}
}
}
if(d[t] == INF) return false;
Flow += a[t];
Cost += d[t] * a[t];
int u = t;
while(u != s) {
Edge[p[u]].f += a[t];
Edge[p[u]^1].f -= a[t];
u = Edge[p[u]].u;
}
return true;
}
int Mincost(int s, int t) {
int Flow = 0, Cost = 0;
while(SPFA(s, t, Flow, Cost)) ;
return Cost;
}
};
MCMF <MAXN+10, MAXM+10> sap;
int main()
{
int n, m;
SF("%d%d", &n, &m);
sap.init(n);
for(int i = 1; i <= m; i++)
{
int u, v, c, cost;
SF("%d%d%d%d", &u, &v, &c, &cost);
sap.add(u, v, c, cost);
}
int ans = sap.Mincost(1, n);
PF("%d", ans);
}
[存模板]最小费用最大流 MCMF
最新推荐文章于 2020-07-19 15:46:29 发布