最小费用最大流模板

const int inf = 0x3f3f3f3f;
const int N = 110, M = N*N;
int Maxflow;
struct EG{
    int u, v, cap, cost;
    EG(){}
    EG(int u, int v, int cap, int cost): u(u), v(v), cap(cap), cost(cost){}
} eg[M];
int tot;
int first[N], Next[M];
void init()
{
    tot = -1;
    Maxflow = 0;
    memset(first, -1, sizeof(first));
}
void add_edge(int u, int v, int cap, int cost)
{
    eg[++tot] = EG(u, v, cap, cost);
    Next[tot] = first[u], first[u] = tot;
    eg[++tot] = EG(v, u, 0, -cost);
    Next[tot] = first[v], first[v] = tot;
}

int dis[N], pre[N];
bool inq[N];
bool spfa(int s, int t)
{
    memset(dis, 0x3f, sizeof(dis));
    memset(inq, 0, sizeof(inq));
    queueq;
    dis[s] = 0, inq[s] = 1; q.push(s);
    while(!q.empty())
    {
        int u = q.front(); q.pop(); inq[u] = 0;
        for(int i=first[u]; i!=-1; i=Next[i])
        {
            EG&e = eg[i];
            if(e.cap > 0 && dis[e.v] > dis[u] + e.cost)
            {
                dis[e.v] = dis[u] + e.cost;
                pre[e.v] = i;
                if(!inq[e.v])
                    inq[e.v] = 1, q.push(e.v);
            }
        }
    }
    return dis[t] != inf;
}
int MCMF(int s, int t)
{
    int ans = 0;
    while(spfa(s,t))
    {
        int mn = inf;
        for(int i=t; i!=s; i=eg[pre[i]].u)
            mn = min(mn, eg[pre[i]].cap);
        for(int i=t; i!=s; i=eg[pre[i]].u)
            eg[pre[i]].cap -= mn,
            eg[pre[i]^1].cap += mn;
        Maxflow += mn;
        ans += mn * dis[t];
    }
    return ans;
}



你可能感兴趣的:(网络流之费用流)