POJ 1273 (Dinic模板 + 当前弧优化)

版权声明:get busy living...or get busy dying https://blog.csdn.net/qq_41444888/article/details/88665419

昨天晚上看明白,今天下午把板子打出来

Dinic简单概括就是

1,利用bfs寻路分层,保证每一次只能从第x层走到第x+1层,省去了很多冗余时间

2,利用dfs递归更新增广路径,如果找不到继续执行步骤1

3,如果步骤1无法分层成功,证明不存在从源点到汇点的一条可行路径,退出程序

当前弧优化:

在此基础上加上当前弧优化,即如果此次dfs进行到点i的时候无法继续搜索,我们下次bfs重新分层后继续从i点开始寻路,而不是从起点开始,这样省去了很多重复的时间

Dinic模板告成,继续SAP的学习

学习博客:

https://www.cnblogs.com/SYCstudio/p/7260613.html

题目链接:

https://cn.vjudge.net/problem/POJ-1273

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 205;
int cnt, st, en;
int n, m;
int u, v, w;
struct node
{
    int to, next, w;
}e[maxn*2];
int head[maxn], depth[maxn], cur[maxn];
void init()
{
    st = 1, en = n;
    cnt = 0;
    memset(head, -1, sizeof(head));
}
void addedge(int u, int v, int w)
{
    e[cnt].w = w;
    e[cnt].to = v;
    e[cnt].next = head[u];
    head[u] = cnt ++;

    e[cnt].w = 0;
    e[cnt].to = u;
    e[cnt].next = head[v];
    head[v] = cnt ++;
}
int dfs(int u, int flow)
{
    if(u == en) return flow;
    for(int& i = cur[u]; ~i; i = e[i].next)
    {
        if(depth[e[i].to] == depth[u] + 1 && (e[i].w != 0))
        {
            int zen = dfs(e[i].to, min(e[i].w, flow));
            if(zen)
            {
                e[i].w -= zen;
                e[i^1].w += zen;
                return zen;
            }
        }
    }
    return 0;
}
int bfs()
{
    queue<int> q;
    while(! q.empty()) q.pop();
    memset(depth, 0, sizeof(depth));
    depth[st] = 1;
    q.push(st);
    while(! q.empty())
    {
        int h = q.front();
        q.pop();
        for(int i = head[h]; ~i; i = e[i].next)
        {
            if((! depth[e[i].to]) && e[i].w)
            {
                depth[e[i].to] = depth[h] + 1;
                q.push(e[i].to);
            }
        }
    }
    if(depth[en]) return 1;
    return 0;
}
int dinic()
{
    int ans = 0;
    while(bfs())
    {
        for(int i = 1; i <= n; i ++)
            cur[i] = head[i];
        while(int d = dfs(st, inf))
            ans += d;
    }
    return ans;
}
int main()
{
    while(scanf("%d%d", &m, &n) != EOF)
    {
        init();
        for(int i = 1; i <= m; i ++)
        {
            scanf("%d%d%d", &u, &v, &w);
            addedge(u, v, w);
        }
        printf("%d\n", dinic());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41444888/article/details/88665419