HDU3549最大流模板学习题

题目链接


http://acm.hdu.edu.cn/showproblem.php?pid=3549
 前几天比赛发现自己的最大流最小割知识忘的一干二尽竟是一朝回到解放前,于是重新学习最大流。EK算法,其实就是BFS求增广路,增广条件是向前的边或是未满的正向边或是大于0的反向边,这样每次增广必然可以让t节点获得值增加

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 20;
const int INF = 0x3f3f3f3f;
int n, m;
struct Edge
{
    int from, to, cap, flow;
    Edge(int from, int to, int cap, int flow):from(from), to(to), cap(cap), flow(flow){}
};
struct EdmondsKarp
{
    vector<Edge> edges;
    vector<int>G[maxn];
    int a[maxn];
    int p[maxn];
    void init(int n)
    {
        for(int i = 0;i < n;i++)
            G[i].clear();
        edges.clear();
    }
    void AddEdge(int from, int to, int cap)
    {
        edges.push_back(Edge(from, to, cap, 0));
        edges.push_back(Edge(to, from, 0, 0));
        int m = edges.size();
        G[from].push_back(m - 2);
        G[to].push_back(m - 1);
    }
    int Maxflow(int s, int t)
    {
        int flow = 0;
        for(;;)
        {
            memset(a, 0, sizeof(a));
            queue<int>Q;
            Q.push(s);
            a[s] = INF;
            while(!Q.empty())
            {
                int x = Q.front();
                Q.pop();
                for(int i = 0;i < (int)G[x].size();i++)
                {
                    Edge &e = edges[G[x][i]];
                    if(!a[e.to]&&e.cap > e.flow)
                    {
                        p[e.to] = G[x][i];
                        a[e.to] = min(a[x], e.cap - e.flow);
                        Q.push(e.to);
                    }
                }
                if(a[t])
                    break;
            }
            if(!a[t])
                break;
            for(int u = t;u != s;u = edges[p[u]].from)
            {
                edges[p[u]].flow += a[t];
                edges[p[u]^1].flow -= a[t];
            }
            flow += a[t];
        }
        return flow;
    }
}ek;
int main()
{
    int t;
    scanf("%d", &t);
    int kase = 1;
    while(t--)
    {
        scanf("%d%d", &n, &m);
        ek.init(n);
        for(int i = 1;i <= m;i++)
        {
            int a, b, c;
            cin>>a>>b>>c;
            a--;
            b--;
            ek.AddEdge(a, b, c);
        }
        cout<<"Case "<<kase++<<": "<<ek.Maxflow(0, n - 1)<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值