【BZOJ2661】连连看

本文介绍了一种基于最小费用最大流算法的具体实现过程。该算法应用于解决特定类型的网络流问题,通过寻找从源点到汇点的最大流量及相应的最小费用路径。文中详细展示了算法的流程,包括初始化网络图、使用SPFA算法进行最短路径搜索、更新残余网络等步骤,并最终输出了最大流及其总费用。

【题目链接】

【思路要点】

  • 补档博客,无题解。

【代码】

#include<bits/stdc++.h>
using namespace std;
#define MAXN	1005
#define INF	1e9
#define MAXQ	1000005
template <typename T> void read(T &x) {
	x = 0; int f = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
	for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
	x *= f;
}
struct edge {int dest, flow, cost; unsigned home; };
int n, m, s, t, tot, len, flow, cost;
int inp[MAXN], outp[MAXN];
int dist[MAXN], path[MAXN];
unsigned home[MAXN];
vector <edge> a[MAXN];
vector <int> b[MAXN];
bool visited[MAXN], colour[MAXN];
void flow_path() {
	int p = t, ans = INF;
	while (p != s) {
		ans = min(ans, a[path[p]][home[p]].flow);
		p = path[p];
	}
	flow += ans, cost += ans * len;
	p = t;
	while (p != s) {
		a[path[p]][home[p]].flow -= ans;
		a[p][a[path[p]][home[p]].home].flow += ans;
		p = path[p];
	}
}
bool spfa() {
	static int q[MAXQ];
	static bool inq[MAXN];
	int l = 0, r = 0;
	q[0] = s, inq[s] = true, dist[s] = 0;
	while (l <= r) {
		int tmp = q[l++];
		inq[tmp] = false;
		for (unsigned i = 0; i < a[tmp].size(); i++)
			if (a[tmp][i].flow != 0 && dist[a[tmp][i].dest] < dist[tmp] + a[tmp][i].cost) {
				dist[a[tmp][i].dest] = dist[tmp] + a[tmp][i].cost;
				path[a[tmp][i].dest] = tmp;
				home[a[tmp][i].dest] = i;
				if (!inq[a[tmp][i].dest]) {
					inq[a[tmp][i].dest] = true;
					q[++r] = a[tmp][i].dest;
				}
			}
	}
	len = dist[t];
	for (int i = 0; i <= r; i++)
		dist[q[i]] = -INF;
	return len != -INF;
}
void addedge(int s, int t, int flow, int cost) {
	a[s].push_back((edge) {t, flow, cost, a[t].size()});
	a[t].push_back((edge) {s, 0, -cost, a[s].size() - 1});
}
int gcd(int x, int y) {
	if (y == 0) return x;
	else return gcd(y, x % y);
}
void work(int pos) {
	visited[pos] = true;
	for (unsigned i = 0; i < b[pos].size(); i++)
		if (!visited[b[pos][i]]) {
			colour[b[pos][i]] = !colour[pos];
			work(b[pos][i]);
		}
}
int main() {
	read(n), read(m);
	for (int i = n; i <= m; i++)
	for (int j = i + 1; j <= m; j++) {
		int tmp = j * j - i * i;
		int tnp = sqrt(tmp);
		if (tnp == sqrt(tmp) && gcd(tnp, i) == 1) {
			b[i].push_back(j);
			b[j].push_back(i);
		}
	}
	for (int i = n; i <= m; i++)
		if (!visited[i]) work(i);
	s = 0, t = m + 1;
	for (int i = n; i <= m; i++)
		if (colour[i]) {
			addedge(s, i, 1, 0);
			for (unsigned j = 0; j < b[i].size(); j++)
				addedge(i, b[i][j], 1, i + b[i][j]);
		} else addedge(i, t, 1, 0);
	for (int i = 0; i <= m + 1; i++)
		dist[i] = -INF;
	while (spfa())
		flow_path();
	cout << flow << ' ' << cost << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值