Kuangbin网络流模板

Kuangbin网络流模板。

const int maxn=20010;
const int maxm=200010;
const double INF=1e20;
const double eps=1e-8;
struct Edge{
    int to,next;
    double cap,flow;
}edge[maxm],tmpG[maxm];

int n,tot,toth,totv;
int head[maxn],tmph[maxn];
int gap[maxn],dep[maxn],cur[maxn];

void addedge(int u,int v,double w,double rw=0){
    edge[tot].to=v;edge[tot].cap=w;edge[tot].flow=0;
    edge[tot].next=head[u];head[u]=tot++;
    edge[tot].to=u;edge[tot].cap=rw;edge[tot].flow=0;
    edge[tot].next=head[v];head[v]=tot++;
}


int Q[maxn];
void BFS(int s,int e){
    memset(dep,-1,sizeof(dep));
    memset(gap,0,sizeof(gap));
    gap[0]=1;
    int front=0,rear=0;
    dep[e]=0;
    Q[rear++]=e;
    while(front!=rear){
        int u=Q[front++];
        for(int i=head[u];i!=-1;i=edge[i].next){
            int v=edge[i].to;
            if(dep[v]==-1) continue;
            Q[rear++]=v;
            dep[v]=dep[u]+1;
            gap[dep[v]]++;
        }
    }
}

int S[maxn];
int sap(int s,int e,int n){
    BFS(s,e);
    memcpy(cur,head,sizeof(head));
    int top=0;int u=s;double ans=0;
    while(dep[s]<n){
        if(u==e){
            double Min=INF;
            int inser;
            for(int i=0;i<top;i++)
                if(Min>edge[S[i]].cap-edge[S[i]].flow){
                    Min=edge[S[i]].cap-edge[S[i]].flow;
                    inser=i;
                }
            for(int i=0;i<top;i++){
                edge[S[i]].flow+=Min;
                edge[S[i]^1].flow-=Min;
            }
            ans+=Min;top=inser;u=edge[S[top]^1].to;
            continue;
        }
        bool flag=false;
        int v;
        for(int i=cur[u];i!=-1;i=edge[i].next){
            v=edge[i].to;
            if(edge[i].cap-edge[i].flow&&dep[v]+1==dep[u]){
                flag=true;cur[u]=i;break;
            }
        }
        if(flag){
            S[top++]=cur[u];u=v;continue;
        }
        int Min=n;
        for(int i=head[u];i!=-1;i=edge[i].next)
            if(edge[i].cap-edge[i].flow&&dep[edge[i].to]<Min){
                Min=dep[edge[i].to];cur[u]=i;
            }
        gap[dep[u]]--;
        if(!gap[dep[u]]) return ans;
        dep[u]=Min+1;
        gap[dep[u]]++;
        if(u!=s) u=edge[S[--top]^1].to;
    }
    return ans;
}
View Code

 

posted on 2016-03-22 11:32  onlyAzha  阅读(326)  评论(0编辑  收藏  举报

导航