最大流朴素算法

#include <iostream>
#include <vector>
#define N 20000
#define INF 2<<29
#define LL long long int
using namespace std;
int n,m;
struct Node
{
    int to;
    LL cap;
    unsigned long rev;
};
LL Min(LL a,LL b)
{
    return a>b?b:a;
}
vector<Node> g[N];
int used[N];
LL dfs(int now,LL f)
{
    if(now==n)
        return f;
    used[now]=1;
    for(int i=0;i<g[now].size();i++)
    {
        Node &e=g[now][i];
        if(!used[e.to]&&e.cap>0)
        {
            //used[e.to]=1;
            LL temp=dfs(e.to,Min(f,e.cap));
            if(temp>0)
            {
                e.cap-=temp;
                g[e.to][e.rev].cap+=temp;
                return temp;
            }
        }
    }
    return 0;
}
void addEdge(int from,int to,LL cap)
{
    g[from].push_back((Node){to,cap,g[to].size()});
    g[to].push_back((Node){from,0,g[from].size()-1});
}
LL solve()
{
    LL ans=0;
    for(;;)
    {
        fill(used,used+n+1,0);
        LL d=dfs(1,INF);
        if(d==0)
            return ans;
        ans+=d;
    }
}
void ini()
{
    for(int i=0;i<=n;i++)
        g[i].clear();
    fill(used,used+n+1,0);
}
int main(int argc, const char * argv[]) {
    cin.sync_with_stdio(false);
    while(cin>>m>>n)
    {
        ini();
        for(int i=0;i<m;i++)
        {
            LL x,y,c;
            cin>>x>>y>>c;
            addEdge(x,y,c);
        }
        
        cout<<solve()<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/LukeStepByStep/p/5817096.html