HDU 2426 Interesting Housing Problem
题意:n个学生,m个房间,给定一些学生想住房的喜欢度,找一个最优方案使得每个学生分配一个房间,并且使得喜欢度最大,注意这题有个坑,就是学生不会住喜欢度为负的房间
思路:很明显的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; 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) { this->n = n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) g[i][j] = -INF; } void add_Edge(int u, int v, Type val) { g[u][v] = max(g[u][v], val); } bool dfs(int i) { S[i] = true; for (int j = 0; j < n; 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 < n; i++) if (!T[i]) a = min(a, slack[i]); for (int i = 0; i < n; i++) { if (S[i]) Lx[i] -= a; if (T[i]) Ly[i] += a; } } int km(int tot) { for (int i = 0; i < n; i++) { left[i] = -1; right[i] = -1; Lx[i] = -INF; Ly[i] = 0; for (int j = 0; j < n; j++) Lx[i] = max(Lx[i], g[i][j]); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) slack[j] = INF; while (1) { for (int j = 0; j < n; j++) S[j] = T[j] = false; if (dfs(i)) break; else update(); } } int ans = 0; for (int i = 0; i < tot; i++) { if (right[i] == -1) return -1; if (g[i][right[i]] == -1) return -1; ans += g[i][right[i]]; } return ans; } } gao; int n, m, k; int main() { int cas = 0; while (~scanf("%d%d%d", &n, &m, &k)) { gao.init(max(n, m)); int u, v, w; while (k--) { scanf("%d%d%d", &u, &v, &w); if (w >= 0) gao.add_Edge(u, v, w); } printf("Case %d: %d\n", ++cas, gao.km(n)); } return 0; }
时间: 2024-10-11 03:07:26