奔小康賺大錢
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
傳說在遙遠的地方有一個非常富裕的村落,有一天,村長決定進行制度改革:重新分配房子。
這可是一件大事,關係到人民的住房問題啊。村裏共有n間房間,剛好有n家老百姓,考慮到每家都要有房住(如果有老百姓沒房子住的話,容易引起不安定因素),每家必須分配到一間房子且只能得到一間房子。
另一方面,村長和另外的村領導希望得到最大的效益,這樣村裏的機構纔會有錢.由於老百姓都比較富裕,他們都能對每一間房子在他們的經濟範圍內出一定的價格,比如有3間房子,一家老百姓可以對第一間出10萬,對第2間出2萬,對第3間出20萬.(當然是在他們的經濟範圍內).現在這個問題就是村領導怎樣分配房子才能使收入最大.(村民即使有錢購買一間房子但不一定能買到,要看村領導分配的).
Input
輸入數據包含多組測試用例,每組數據的第一行輸入n,表示房子的數量(也是老百姓家的數量),接下來有n行,每行n個數表示第i個村名對第j間房出的價格(n<=300)。
Output
請對每組數據輸出最大的收入值,每組的輸出佔一行。
Sample Input
2
100 10
15 23
Sample Output
123
知識點:二分圖最大權匹配
知識點算法詳解請參見:http://www.cnblogs.com/wenruo/p/5264235.html
AC代碼:
# include <cstdio>
# include <cstring>
# include <algorithm>
using namespace std;
# define MAXN 305
# define INF 100000000
int love[MAXN][MAXN];
int exhome[MAXN];
int expeople[MAXN];
int vishome[MAXN];
int vispeople[MAXN];
int match[MAXN];
int slack[MAXN];
int n;
bool dfs(int people)
{
vispeople[people] = 1;
for (int home = 0; home < n; home++)
{
if (vishome[home])
{
continue;
}
int gap = expeople[people] + exhome[home] - love[people][home];
if (!gap)
{
vishome[home] = 1;
if (-1 == match[home] || dfs(match[home]))
{
match[home] = people;
return true;
}
}
else if (gap < slack[home])
{
slack[home] = gap;
}
}
return false;
}
int KM()
{
int i, j;
memset(match, -1, sizeof(match));
memset(exhome, 0, sizeof(exhome));
for (i = 0; i < n; i++)
{
expeople[i] = love[i][0];
for (j = 1; j < n; j++)
{
if (love[i][j] > expeople[i])
{
expeople[i] = love[i][j];
}
}
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
slack[j] = INF;
}
while (1)
{
memset(vispeople, 0, sizeof(vispeople));
memset(vishome, 0, sizeof(vishome));
if (dfs(i))
{
break;
}
int d = INF;
for (j = 0; j < n; j++)
{
if (!vishome[j])
{
if (slack[j] < d)
{
d = slack[j];
}
}
}
for (j = 0; j < n; j++)
{
if (vispeople[j])
{
expeople[j] -= d;
}
if (vishome[j])
{
exhome[j] += d;
}
else
{
slack[j] -= d;
}
}
}
}
int res = 0;
for (i = 0; i < n; i++)
{
if (-1 != match[i])
{
res += love[match[i]][i];
}
}
return res;
}
int main(void)
{
while (~scanf("%d", &n))
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &love[i][j]);
}
}
printf("%d\n", KM());
}
return 0;
}