Dinic 成功死在了评测机上,求解!!
查看原帖
Dinic 成功死在了评测机上,求解!!
800884
Weekoder楼主2025/1/18 20:13

rt,EK 46ms,Dinic 8.42s。。。

#include <bits/stdc++.h>

#define debug(x) (cout << #x << " " << x << "\n")

using namespace std;

using ll = long long;

const int N = 1e4 + 5;

const int dx[] = {-1, 0, 0, 1};
const int dy[] = {0, -1, 1, 0};

struct Edge {
	ll to, w, bk;
};

ll n, m, s, t, inc[N], pre[N], lst[N], level[N], tmp[N], a[105][105], sum;

vector<Edge> nbr[N];

int id(int i, int j) { return (i - 1) * m + j; }

void add(ll u, ll v, ll w) {
	nbr[u].emplace_back((Edge){v, w, nbr[v].size()});
	nbr[v].emplace_back((Edge){u, 0, nbr[u].size() - 1});
}

bool bfs() {
	fill(level + 1, level + 2 + n * m, 0);
	fill(tmp + 1, tmp + 2 + n * m, 0); 
	queue<ll> q;
	q.push(s);
	level[s] = 1;
	while (!q.empty()) {
		ll cur = q.front(); q.pop();
		for (ll i = 0; i < nbr[cur].size(); i++) if (!level[nbr[cur][i].to] && nbr[cur][i].w) {
			ll nxt = nbr[cur][i].to, w = nbr[cur][i].w;
			q.push(nxt);
			level[nxt] = level[cur] + 1;
			if (nxt == t) return 1;
		}
	}
	return 0;
}

ll dfs(ll cur, ll flow) {
	if (cur == t) return flow;
	ll rest = flow;
	for (ll i = tmp[cur]; i < nbr[cur].size() && rest; i++) {
		tmp[cur] = i;
		ll nxt = nbr[cur][i].to, w = nbr[cur][i].w;
		if (w && level[nxt] == level[cur] + 1) {
			ll inc = dfs(nxt, min(rest, w));
			if (!inc) level[nxt] = 0;
			nbr[cur][i].w -= inc;
			nbr[nxt][nbr[cur][i].bk].w += inc;
			rest -= inc;
		}	
	}
	return flow - rest;
}

ll dinic() {
	ll maxflow = 0;
	while (bfs()) maxflow += dfs(s, 1e18);
	return maxflow;
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n >> m;
	s = 0, t = n * m + 1;
	for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) {
		cin >> a[i][j], sum += a[i][j];
	}
	for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) {
		if ((i + j) % 2) {
			add(s, id(i, j), a[i][j]);
			for (int d = 0; d < 4; d++) {
				int nx = i + dx[d], ny = j + dy[d];
				if (nx >= 1 && nx <= n && ny >= 1 && ny <= m) add(id(i, j), id(nx, ny), 1e18);
			}
		} else {
			add(id(i, j), t, a[i][j]);
		}
	}
	cout << sum - dinic();
	return 0;
}

由于我怀疑我犯下了唐诗错误,此贴会在得到解答后迅速删掉。

2025/1/18 20:13
加载中...