二分图最大权值匹配模板 hdu 2255

                     奔小康赚大钱

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2132    Accepted Submission(s): 924


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
 代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=310;
const int inf=2147483647;
int weight[maxn][maxn],lx[maxn],ly[maxn],match[maxn],n;
bool sx[maxn],sy[maxn];
bool path(int u)
{
      sx[u]=1;
      for(int v=0;v<n;v++)
      if(!sy[v]&&lx[u]+ly[v]==weight[u][v])
      {
            sy[v]=1;
            if(match[v]==-1||path(match[v]))
            {
                  match[v]=u;
                  return 1;
            }
      }
      return 0;
}
int km(int max_weight)
{
      int i,j,k;
      if(!max_weight)
      {
           for(i=0;i<n;i++)
                  for(j=0;j<n;j++)weight[i][j]=-weight[i][j];
      }
      for(i=0;i<n;i++)
      {
           ly[i]=0;
           lx[i]=-inf;
           for(j=0;j<n;j++)if(weight[i][j]>lx[i])lx[i]=weight[i][j];
      }
      memset(match,-1,sizeof(match));
      for(int u=0;u<n;u++)
      while(1)
      {
            memset(sx,0,sizeof(sx));
            memset(sy,0,sizeof(sy));
            if(path(u))break;
            int cnt=inf;
            for(i=0;i<n;i++)
            if(sx[i])
            for(j=0;j<n;j++)
            if(!sy[j]&&lx[i]+ly[j]-weight[i][j]<cnt)
            cnt=lx[i]+ly[j]-weight[i][j];
            if(cnt==0)break;
            for(i=0;i<n;i++)
            {
                  if(sx[i])lx[i]-=cnt;
                  if(sy[i])ly[i]+=cnt;
            }
      }
      int ans=0;
      for(i=0;i<n;i++)
            if(match[i]>=0)ans+=weight[match[i]][i];
      if(max_weight==0)ans=-ans;
      return ans;
}
int main()
{
      int T;
      scanf("%d",&T);
      while(T--)
      {
            scanf("%d",&n);
            for(int i=0;i<n;i++)
                  for(int j=0;j<n;j++)scanf("%d",&weight[i][j]);
            printf("%d\n",km(1));
      }
      return 0;
}


posted @ 2013-08-01 00:02  线性无关  阅读(149)  评论(0)    收藏  举报