网络流二:最大流(高阶)Dinic算法(bfs + dfs)

//网络流最大流Dinic算法(高阶) 
//Ps 要求出最大流中每条边的流量,怎么办?
//将原图备份,原图上的边的容量减去做完最大流的残余网络上的边的剩余容量,就是边的流量。
// --------
//在普通情况下, DINIC算法时间复杂度为O(V2E) 
//在二分图中, DINIC算法时间复杂度为O(√VE)
//https://blog.csdn.net/A_Comme_Amour/article/details/79356220
// 无法自动去重边 
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

#define maxn 0x7fffffff
const int inf = 1e9;

int n, m, sta, tag;

struct stu{
	int next, to, w;
};
stu edge[100010 * 2];

int deep[10010] = {0}; // 记录bfs分图的深度 
int edgeNum = -1;
int head[10010] = {0};
int cur[10010] = {0}; // 用来copy head 
int maxFlow = 0;
queue<int>qu;

int read()
{
	int x = 0, w = 1;
	char ch = getchar();
	while(ch <='0' || ch > '9')
	{
		if(ch == '-') w = -1;
		ch = getchar();
	}
	while(ch <= '9' && ch >= '0')
	{
		x = x * 10 + ch - '0';
		ch = getchar();
	}
	return x * w;
}

void add_edge(int from, int to, int w)
{
	edge[++edgeNum].next = head[from];
	edge[edgeNum].to = to;
	edge[edgeNum].w = w;
	head[from] = edgeNum;
}

// bfs用来分层 提高dfs顺序 
bool bfs(int s, int t)
{
	memset(deep, 0x7f, sizeof(deep)); // deep的初始值大于1e9 即0x7fffffff 
	while(!qu.empty()) qu.pop();
	for(int i = 1; i <= n; i++)
	{
		cur[i] = head[i];
	}
	deep[s] = 0;
	qu.push(s);
	
	while(!qu.empty())
	{
		int now = qu.front();
		qu.pop();
		for(int i = head[now]; i != -1; i = edge[i].next)
		{
			int to = edge[i].to;
			int w = edge[i].w;
			if(deep[to] > inf && w) // 特判 防止反向边干扰 
			{
				deep[to] = deep[now] + 1;
				qu.push(to);
			}
		}
	}
	if(deep[t] < inf) return true;
	return false;
}

int dfs(int now, int t, int minn)
{
	if(minn == 0 || now == t) // 边的残留量为零无法增广 或 搜索到t完成增广 
	{
		return minn;
	}
	int flow = 0, f; // flow为该点增广出去所有增量的和  f暂时存储下一点的dfs值 
	for(int i = cur[now]; i != -1; i = edge[i].next)
	{
		cur[now] = i; // 如果一条边被搜到的话,我们会利用完它所有价值,此时这条边就没有用了
//cur为了当前弧优化。已经增广的边就不需要再走了 
		int to = edge[i].to;
		int w = edge[i].w;
		if(deep[to] == deep[now] + 1 && (f = dfs(to, t, min(minn, w))))
		{
			flow += f;
			minn -= f;
			edge[i].w -= f;
			edge[i ^ 1].w += f; // 异或取反边 
			if(minn == 0) break;
		}
	}
	return flow;
}

void Dinic(int s, int t)
{
	while(bfs(s, t))
	{
		maxFlow += dfs(s, t, maxn);
	}
}

int main()
{
	n = read();
	m = read();
	sta = read();
	tag = read();
	
	memset(head, -1, sizeof(head)); // 编译异或直接得反向边 
	
	for(int i = 1; i <= m; i++)
	{
		int a = read();
		int b = read();
		int c = read();
		add_edge(a, b, c);
		add_edge(b, a, 0); //建立反向边 反向边的边权为 0
	}
	Dinic(sta, tag);
	printf("%d", maxFlow);
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值