Network flow board

The maximum flow dinic board

const int N = 1e6+10, S = N-2, T = N-1, INF = 0x3f3f3f3f;
int n;
struct edge {
    int to,w,next;
    edge(int to=0,int w=0,int next=0):to(to),w(w),next(next){}
} e[N];
int head[N], dep[N], vis[N], cur[N], cnt=1;
queue<int> Q;
void add(int u, int v, int w) {
    e[++cnt] = edge(v,w,head[u]);
    head[u] = cnt;
    e[++cnt] = edge(u,0,head[v]);
    head[v] = cnt;
}
int bfs() {
    REP(i,1,n) dep[i]=INF,vis[i]=0,cur[i]=head[i];
    dep[S]=INF,vis[S]=0,cur[S]=head[S];
    dep[T]=INF,vis[T]=0,cur[T]=head[T];
    dep[S]=0,Q.push(S);
    while (Q.size()) {
        int u = Q.front(); Q.pop();
        for (int i=head[u]; i; i=e[i].next) {
            if (dep[e[i].to]>dep[u]+1&&e[i].w) {
                dep[e[i].to]=dep[u]+1;
                Q.push(e[i].to);
            }
        }
    }
    return dep[T]!=INF;
}
int dfs(int x, int w) {
    if (x==T) return w;
    int used = 0;
    for (int i=cur[x]; i; i=e[i].next) {
        cur[x] = i;
        if (dep[e[i].to]==dep[x]+1&&e[i].w) {
            int f = dfs(e[i].to,min(w-used,e[i].w));
            if (f) used+=f,e[i].w-=f,e[i^1].w+=f;
            if (used==w) break;
        }
    }
    return used;
}
int dinic() {
    int years = 0; 
    while (bfs ()) = + years dfs (S INF); 
    return years; 
}

Cost Flow EK + spfa board

const int N = 1e6+10, INF = 0x3f3f3f3f, S = N-2, T = N-1;
int n, m, flow, cost;
struct edge {
    int to,w,v,next;
    edge(int to=0,int w=0,int v=0,int next=0):to(to),w(w),v(v),next(next){}
} e[N];
int head[N], dep[N], vis[N], cur[N], f[N], cnt=1;
int pre[N],pre2[N];
queue<int> Q;
void add(int u, int v, int w, int k) {
    e[++cnt] = edge(v,w,k,head[u]);
    head[u] = cnt;
    e[++cnt] = edge(u,0,-k,head[v]);
    head[v] = cnt;
}
int spfa() {
    REP(i,1,n) f[i]=dep[i]=INF,vis[i]=0;
    f[S]=dep[S]=f[T]=dep[T]=INF;
    dep[S]=0,Q.push(S);
    while (Q.size()) {
        int u = Q.front(); Q.pop();
        vis[u] = 0;
        for (int i=head[u]; i; i=e[i].next) {
            if (dep[e[i].to]>dep[u]+e[i].v&&e[i].w) {
                dep[e[i].to]=dep[u]+e[i].v;
				pre[e[i].to]=u,pre2[e[i].to]=i;
                f[e[i].to]=min(f[u],e[i].w);
                if (!vis[e[i].to]) {
                    vis[e[i].to]=1;
                    Q.push(e[i].to);
                }
            }
        }
    }
    return dep[T]!=INF;
}
void EK(){
    while(spfa()) {
        int w = f[T];
        for (int u=T; u!=S; u=pre[u]) {
            e[pre2[u]].w-=w;
            e[pre2[u]^1].w+=w;
        }
        flow += w, cost += w*dep[T];
    }
}

 

Guess you like

Origin www.cnblogs.com/uid001/p/11070064.html