码迷,mamicode.com
首页 > 编程语言 > 详细

【模板】dinic算法网络最大流

时间:2019-11-09 00:03:06      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:break   res   bsp   push   nic   div   i++   for   网络最大流   

void add_dinic(int u, int v)
{
    e[++cnt].v = v;
    e[cnt].w = 0;
    e[cnt].nxt = head[u];
    head[u] = cnt;
}

int dfs_dinic(int x, int flow)
{
    if (x == ed) return flow;
    int res = 0;
    for (int i = now[x]; i != -1; i = e[i].nxt)
    {
        int v = e[i].v;
        if (d[v] + 1 == d[x] && e[i].w > 0)
        {
            int k = dfs_dinic(v, min(e[i].w, flow));
            res += k;
            flow -= k;
            e[i].w -= k;
            e[i ^ 1].w += k;
            if (!flow) break;
        }
    }
    return res;
}

bool bfs_dinic()
{
    memset(d, 0, sizeof(d));
    queue<int>q;
    q.push(ed);
    d[ed] = 1;
    while (!q.empty())
    {
        int u = q.front();
        q.pop();
        for (int i = head[u]; i != -1; i = e[i].nxt)
        {
            int v = e[i].v;
            if (!d[v] && e[i ^ 1].w > 0)
            {
                q.push(v);
                d[v] = d[u] + 1;
            }
        }
    }
    return d[st] > 0;
}


int dinic() 
{
    int flow = 0;
    while (bfs_dinic()) 
    {
        for (int i = 0; i <= ed; i++) now[i] = head[i];
        flow += dfs_dinic(st, INF);
    }
    return flow;
}

 

【模板】dinic算法网络最大流

标签:break   res   bsp   push   nic   div   i++   for   网络最大流   

原文地址:https://www.cnblogs.com/thjkhdf12/p/11823731.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!