网络流之最大流-Ford-Fullkerson算法 DFS && BFS

理解处

DFS

#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <cstring>

using namespace std;
const int max_v = 1000;
const int INF = 0x3f3f3f3f;

struct edge
{
    int to,cap,rev;   //rev是反向边的编号,即这条反向边是以to为起点的第几条边
};

vector<edge> G[max_v];
bool used[max_v];
void add(int from,int to,int cap)
{
    G[from].push_back((edge){to,cap,G[to].size()});//因为下一步要加一条反向边,所以不需要-1
    G[to].push_back((edge){from,0,G[from].size()-1});
}
int dfs(int v,int t,int f)
{
    if(v==t) return f;
    used[v]=1;
    for(int i =0;i<G[v].size();++i)
    {
        edge &e = G[v][i];
        if(!used[e.to] && e.cap > 0)
        {
            int d = dfs(e.to,t,min(f,e.cap));
            if(d>0)
            {
                e.cap-=d;
                G[e.to][e.rev].cap+=d;
                return d;//给上一层的d,让上一层也能更新;
            }
        }
    }
    return 0;
}

int  main()
{
    int m,s,t;
    scanf("%d%d%d",&s,&t,&m);

    int from,to,cap;
    for(int i=0;i<m;++i)
    {
        //点从1号开始。
        scanf("%d%d%d",&from,&to,&cap);
        add(from,to,cap);

    }

    int flow=0;
    while(1)
    {
        memset(used,0,sizeof(used));
        int f=dfs(s,t,INF);
        if(f==0) break;
        flow+=f;
    }
    printf("%d",flow);


    return 0;
}

/*
1 4 7
1 2 10
1 5 2
2 5 6
2 3 6
3 4 8
3 5 3
5 4 5
结果:11
*/
View Code

猜你喜欢

转载自www.cnblogs.com/shuaihui520/p/9153164.html