ISAP学习笔记

· · 个人记录

ISAP只进行一遍bfs,每个点的层数随着dfs的进行而不断提高,这样就不用反复跑bfs重新分层了。

当s的深度大于n时,结束算法。

#include <bits/stdc++.h>
using namespace std;

inline int read()
{
    int x=0;int f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

const int MAXN =10005;
const int INF = 0x3f3f3f3f;
struct Edge{int to,cap,rev;};
std::vector <Edge> G[MAXN];
int dep[MAXN],iter[MAXN],gap[MAXN];
int n,m,s,t;

inline void addedge(int u,int v,int w) 
{
    G[u].push_back(Edge{v,w,G[v].size()});
    G[v].push_back(Edge{u,0,G[u].size()-1});
}

inline void bfs(int t) 
{
    memset(gap,0,sizeof(gap));
    memset(dep,-1,sizeof(dep));
    queue<int> q; dep[t]=1; 
    gap[dep[t]]=1; q.push(t);
    while(!q.empty()) 
    {
        int x=q.front(); q.pop();
        for (int i=0; i<G[x].size(); i++) 
        {
            Edge &e=G[x][i];
            if(dep[e.to]<0) 
            {
                dep[e.to]=dep[x]+1;
                gap[dep[e.to]]++;
                q.push(e.to);
            }
        }
    }
}

int dfs(int x,int s,int t,int f) 
{
    if(x==t) return f;
    int flow=0;
    for (int &i=iter[x]; i<G[x].size(); i++) 
    {
        Edge &e=G[x][i];
        if(e.cap>0 && dep[x]==dep[e.to]+1) 
        {
            int d=dfs(e.to,s,t,min(f-flow,e.cap));
            e.cap-=d; G[e.to][e.rev].cap+=d;
            flow+=d;
            if(f==flow) return f;
        }
    }
    gap[dep[x]]--; iter[x]=0;
    if(gap[dep[x]]==0) dep[s]=n+1;
    gap[++dep[x]]++; return flow;
}

inline int isap(int s,int t) 
{
    int flow=0; bfs(t);
    memset(iter,0,sizeof(iter));
    while(dep[s]<=n) flow+=dfs(s,s,t,INF);
    return flow;
}

int main() 
{
    n=read(); m=read();
    s=read(); t=read();
    int u,v,w;
    for (int i=1; i<=m; i++) 
    {
        u=read(),v=read(),w=read();
        addedge(u,v,w);
    }
    printf("%d\n",isap(s,t));
    return 0;
}