最大流 ISAP

const int MAXN = 2010;//点数
const int MAXM = 400010;//正向弧和反向弧的数量
#######################################################################################################################################

struct Edge
{
    int to,next,cap,flow;
} edge[MAXM];


int Top;
int head[MAXN];
int gap[MAXN],dep[MAXN],cur[MAXN];


void Init()
{
    Top = 0;
    memset(head,-1,sizeof(head));
}


void Link(int u,int v,int w)
{
    edge[Top].to = v,edge[Top].cap = w,edge[Top].flow = 0;
    edge[Top].next = head[u],head[u] = Top++;


    edge[Top].to = u,edge[Top].cap = 0,edge[Top].flow = 0;
    edge[Top].next = head[v],head[v] = Top++;
}


int Q[MAXN];


void BFS(int S,int E)
{
    memset(dep,-1,sizeof(dep));
    memset(gap,0,sizeof(gap));
    int u,v,i,Front = 0,Rear = 0;
    dep[E] = 0;
    Q[Rear++] = E;
    gap[0] = 1;


    while(Front != Rear)
    {
        u = Q[Front++];


        for(i = head[u]; i != -1; i = edge[i].next)
        {
            v = edge[i].to;
            if(dep[v] != -1) continue;
            Q[Rear++] = v;
            dep[v] = dep[u] + 1;
            gap[dep[v]]++;
        }
    }
}

int S[MAXN];

int ISAP(int Start,int End,int N)
{
    BFS(Start,End);
    if(dep[Start] == -1)
        return 0;
    memcpy(cur,head,sizeof(head));
    int Top = 0;
    int u = Start,v;
    int flow = 0;
    int Min;
    int inser;
    int i;
    while(dep[Start] < N)
    {
        if(u == End){
            Min = INF,inser = -1;


            for(i = 0;i < Top; ++i)
                if(Min > edge[S[i]].cap - edge[S[i]].flow)
                    inser = i,Min = edge[S[i]].cap - edge[S[i]].flow;


            for(i = 0 ; i < Top; ++i)
                edge[S[i]].flow += Min,edge[S[i]^1].flow -= Min;


            flow += Min;
            Top = inser;
            u = edge[S[Top]^1].to;
            continue;
        }


        bool flag = false;
        for(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(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]] == 0)
            return flow;
        dep[u] = Min+1;
        gap[dep[u]]++;
        if(u != Start) u = edge[S[--Top]^1].to;
    }
    return flow;
}

你可能感兴趣的:(模板)