HDU 2282 Chocolate(KM最大匹配)

HDU 2282 Chocolate

题目链接

题意:一些盒子排成一圈,每次可以移动一个巧克力到相邻盒子,问最少几步能让每个盒子里面巧克力个数<= 1

思路:把一个盒子个数大于1的拆成个数 - 1个点,每个点和空盒子连边,跑KM最大匹配即可

代码:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

const int MAXNODE = 505;

typedef int Type;
const Type INF = 0x3f3f3f3f;

struct KM {
	int n, m;
	Type g[MAXNODE][MAXNODE];
	Type Lx[MAXNODE], Ly[MAXNODE], slack[MAXNODE];
	int left[MAXNODE], right[MAXNODE];
	bool S[MAXNODE], T[MAXNODE];

	void init(int n, int m) {
		this->n = n;
		this->m = m;
	}

	void add_Edge(int u, int v, Type val) {
		g[u][v] = val;
	}

	bool dfs(int i) {
		S[i] = true;
		for (int j = 0; j < m; j++) {
			if (T[j]) continue;
			Type tmp = Lx[i] + Ly[j] - g[i][j];
			if (!tmp) {
				T[j] = true;
				if (left[j] == -1 || dfs(left[j])) {
					left[j] = i;
					right[i] = j;
					return true;
				}
			} else slack[j] = min(slack[j], tmp);
		}
		return false;
	}

	void update() {
		Type a = INF;
		for (int i = 0; i < m; i++)
			if (!T[i]) a = min(a, slack[i]);
		for (int i = 0; i < n; i++)
			if (S[i]) Lx[i] -= a;
		for (int i = 0; i < m; i++)
			if (T[i]) Ly[i] += a;
	}

	Type km() {
		memset(left, -1, sizeof(left));
		memset(right, -1, sizeof(right));
		memset(Ly, 0, sizeof(Ly));
		for (int i = 0; i < n; i++) {
			Lx[i] = -INF;
			for (int j = 0; j < m; j++)
				Lx[i] = max(Lx[i], g[i][j]);
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) slack[j] = INF;
			while (1) {
				memset(S, false, sizeof(S));
				memset(T, false, sizeof(T));
				if (dfs(i)) break;
				else update();
			}
		}
		Type ans = 0;
		for (int i = 0; i < n; i++)
			ans += g[i][right[i]];
		return -ans;
	}
} gao;

const int N = 505;

int n, un, vn, u[N], v[N];

int cal(int u, int v) {
	if (u > v) swap(u, v);
	return min(v - u, n - v + u);
}

int main() {
	while (~scanf("%d", &n)) {
		un = vn = 0;
		int tmp;
		for (int i = 0; i < n; i++) {
			scanf("%d", &tmp);
			for (int j = 1; j < tmp; j++)
				u[un++] = i;
			if (tmp == 0)
				v[vn++] = i;
		}
		gao.init(un, vn);
		for (int i = 0; i < un; i++) {
			for (int j = 0; j < vn; j++) {
				gao.add_Edge(i, j, -cal(u[i], v[j]));
			}
		}
		printf("%d\n", gao.km());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值