网络流最大流板子+一点理解

原理就是内个原理~

最大流==最小割==二分图最小点权覆盖权值和

dc+弧优化

#include<cstdio>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<stdlib.h>
#include<queue> 
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1000000; 
typedef long long LL;
const int N = 20005;
const int INF = 0x3f3f3f3f;
bool vis[N];
struct Edge{
    int to, cap, flow, next;
}edge[N*50];
int n, m, cnt;//n是点 m是边 cnt是加边操作后的边 
int head[N];//邻接表 
int dis[N];//分层 等级 
int  cur[N];//弧优化 
void add(int u, int v, int w){
    edge[cnt] = (struct Edge){v, w, 0, head[u]};
    head[u] = cnt++;
    edge[cnt] = (struct Edge){u, 0, 0, head[v]};
    head[v] = cnt++;
}
 
bool bfs(int start, int endd){//分层 
    memset(dis, -1, sizeof(dis));
    memset(vis, false, sizeof(vis));
    queue<int>que;
    dis[start] = 0;
    vis[start] = true;
    que.push(start);
    while(!que.empty()){
        int u = que.front();
        que.pop();
        for(int i = head[u]; i != -1; i = edge[i].next){
            Edge E = edge[i];
            if(!vis[E.to] && E.flow<E.cap){
                dis[E.to] = dis[u]+1;
                vis[E.to] = true;
                if(E.to == endd) return true;
                que.push(E.to);
            }
        }
    }
    return false;
}
 
int dfs(int x, int res, int endd){ //增广 
	if(x == endd || res == 0) return res;
	int flow = 0, f;
	for(int& i = cur[x]; i != -1; i = edge[i].next){
		Edge E = edge[i];
		if(dis[E.to] == dis[x]+1){
		    f = dfs(E.to, min(res, E.cap-E.flow), endd);
            if(f>0){
                edge[i].flow += f;
                edge[i^1].flow -= f;
                flow += f;
                res -= f;
                if(res == 0) break;
            }
		}
	}
	return flow;
}

int max_flow(int start, int endd){
    int flow = 0;
    while(bfs(start, endd)){
        memcpy(cur, head, sizeof(head));//初始化弧优化数组 
        flow += dfs(start, INF, endd);
    }
    return flow;
}
 
void init(){//初始化 
    cnt = 0;
    memset(head, -1, sizeof(head));
}
int main(){
    scanf("%d%d", &m, &n);
    init();
    int sp=1;//源点 
    int tp=n;//汇点 
    for(int i = 1; i <= m; i++){
    	int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        add(x, y, z);
        add(y, x, z);
    }    
    int ans = max_flow(sp, tp);
    printf("%d\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/gml1999/article/details/89761833
今日推荐