WA#10#11求助(Dinic算法)
查看原帖
WA#10#11求助(Dinic算法)
791248
yinyuxuan楼主2025/7/27 11:19
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, m, s, t, cnt, head[205], dis[205], f[205][205];
struct node
{
	int to, next, cap, flow;
}ed[10005];
void add(int u, int v, int w)
{
	cnt++;
	ed[cnt].to = v;
	ed[cnt].next = head[u];
	head[u] = cnt;
	ed[cnt].cap = w;
	ed[cnt].flow = 0;
}
bool bfs()
{
	memset(dis, 0, sizeof(dis));
	dis[s] = 1;
	queue<int> q; q.push(s);
	while (!q.empty())
	{
		int k = q.front(); q.pop();
		for (int i = head[k]; i; i = ed[i].next)
		{
			int p = ed[i].to;
			if (!dis[p] && ed[i].cap > ed[i].flow)
			{
				dis[p] = dis[k] + 1;
				q.push(p);
			}
		}
	}
	if (dis[t])
		return true;
	return false;
}
int dfs(int p, int minflow)
{
	if (p == t || !minflow)
		return minflow;
	int flow = 0;
	for (int i = head[p]; i; i = ed[i].next)
	{
		if (dis[ed[i].to] == dis[p] + 1 && ed[i].cap > ed[i].flow)
		{
			int f = dfs(ed[i].to, min(ed[i].cap - ed[i].flow, minflow));
			ed[i].flow += f, ed[i + 1].flow -= f;
			flow += f, minflow -= f;
			if (!minflow)
				break;
		}
	}
	return flow;
}
int dinic()
{
	if (s == t)
		return 0;
	int maxflow = 0;
	while (bfs())
		maxflow += dfs(s, INFINITY);
	return maxflow;
}
signed main()
{
	cin >> n >> m >> s >> t;
	for (int i = 1; i <= m; i++)
	{
		int a, b, c; cin >> a >> b >> c;
		if (a != b)
		{
			if (!f[a][b])
			{
				add(a, b, c); add(b, a, 0);
				f[a][b] = cnt - 1;
			}
			else
				ed[f[a][b]].cap += c;
		}
	}
	int ans = dinic();
	cout << ans << endl;
	return 0;
}

测试点信息

2025/7/27 11:19
加载中...