2018-team4-modules-费用流

从 Trac 迁移的文章

这是从旧校内 Wiki 迁移的文章,可能存在一些样式问题,您可以向 memset0 反馈。

原文章内容如下:

{{{
struct Edge{ int a,b,v,cost,next; }e[M],id;
inline void add(int a,int b,int v,int cost) {
    if (!a || !b) return ; 
    e[++cnt] = (Edge){ a,b,v,cost,head[a] }, head[a] = cnt;
    e[++cnt] = (Edge){ b,a,0,-cost,head[b] },head[b] = cnt;
}

#define cp e[i].v  
#define B e[i].b  

bool SPFA() {  
    bool flag = false;
    for (int i=1;i<=tot;i++) p[i] = 0, dis[i] = -(1LL<<62);
    dis[S] = 0;
    queue<int> q; q.push(S);  
    while (!q.empty()) {  
        int u = q.front(); q.pop();  
        if (u == T) flag = true;
        for (int i=head[u];i;i=e[i].next)  
            if (cp > 0 && dis[u] + e[i].cost > dis[B]) {  
                dis[B] = dis[u] + e[i].cost;  
                p[B] = i;  
                q.push(B);  
            }   
    }  
    return flag;  
}  

void mcf() {  
    int g = p[T] , flow = INF;  
    while (g) {
        flow = min(flow , e[g].v);  
        g = p[ e[g].a ];  
    }
    g = p[T];  
    while (g) {  
        e[g  ].v -= flow;  
        e[g^1].v += flow;  
        ans += 1LL * e[g].cost * flow;  
        g = p[ e[g].a ];  
    }
}
}}}
struct Edge{ int a,b,v,cost,next; }e[M],id;
inline void add(int a,int b,int v,int cost) {
    if (!a || !b) return ; 
    e[++cnt] = (Edge){ a,b,v,cost,head[a] }, head[a] = cnt;
    e[++cnt] = (Edge){ b,a,0,-cost,head[b] },head[b] = cnt;
}
#define cp e[i].v  
#define B e[i].b  
bool SPFA() {  
    bool flag = false;
    for (int i=1;i<=tot;i++) p[i] = 0, dis[i] = -(1LL<<62);
    dis[S] = 0;
    queue<int> q; q.push(S);  
    while (!q.empty()) {  
        int u = q.front(); q.pop();  
        if (u == T) flag = true;
        for (int i=head[u];i;i=e[i].next)  
            if (cp > 0 && dis[u] + e[i].cost > dis[B]) {  
                dis[B] = dis[u] + e[i].cost;  
                p[B] = i;  
                q.push(B);  
            }   
    }  
    return flag;  
}  
void mcf() {  
    int g = p[T] , flow = INF;  
    while (g) {
        flow = min(flow , e[g].v);  
        g = p[ e[g].a ];  
    }
    g = p[T];  
    while (g) {  
        e[g  ].v -= flow;  
        e[g^1].v += flow;  
        ans += 1LL * e[g].cost * flow;  
        g = p[ e[g].a ];  
    }
}