题目链接:点击这里

题目大意:
给一张有向图,求 s s s t t t 的最大流

题目分析:
最大流模板,下采用的 d i n i c dinic dinic 算法,即先将图分层(只往层数高的方向增广,可以保证不走回头路也不绕圈子),再在求增广路的过程中加上当前弧优化(因为在 d i n i c dinic dinic 算法中,一条边增广一次后就不会再次增广了,所以下次增广时不需要再考虑这条边)

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<set>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
#define int ll
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 205;
const int maxm = 5005;
const int mod = 998244353;
const double pi = acos(-1);
const double eps = 1e-8;
struct Edge{
	int nxt,to,val;
}edge[maxm<<1];
int n,m,s,t,cnt = 1,head[maxn],cur[maxn],dep[maxn];
void addedge(int from,int to,int val)
{
	edge[++cnt].nxt = head[from];
	edge[cnt].to = to;
	edge[cnt].val = val;
	head[from] = cnt;
}
bool bfs(int s,int t)
{
	memcpy(cur,head,sizeof(head));
	memset(dep,0,sizeof(dep));
	dep[s] = 1;
	queue<int>qu;
	qu.push(s);
	while(!qu.empty())
	{
		int h = qu.front(); qu.pop();
		for(int i = head[h];i;i = edge[i].nxt)
		{
			int to = edge[i].to,val = edge[i].val;
			if(val>0 && !dep[to]) dep[to] = dep[h]+1,qu.push(to);
		}
	}
	return dep[t];
}
int dfs(int now = s,int flow = inf) //s->t 
{
	if(now == t) return flow;
	int rem = flow;
	for(int i = cur[now];i && rem;i = edge[i].nxt)
	{
		cur[now] = i;
		int to = edge[i].to,val = edge[i].val;
		if(val>0 && dep[to]==dep[now]+1)
		{
			int tmp = dfs(to,min(val,rem));
			rem -= tmp;
			edge[i].val -= tmp;
			edge[i^1].val += tmp;
		}
	}
	return flow-rem;
}
int dinic(int s,int t)
{
	int res = 0;
	while(bfs(s,t)) res += dfs();
	return res;
} 
signed main()
{
	n = read(),m = read(),s = read(),t = read();
	for(int i = 1;i <= m;i++)
	{
		int from = read(),to = read(),val = read();
		addedge(from,to,val);
		addedge(to,from,0);
	}
	printf("%lld\n",dinic(s,t));
	return 0;
}
点击阅读全文
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐