HDU 2426

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2426


二分图的最优匹配。用KM算法解决。题目要求找到最大的权值。同时要n个人都要匹配到。注意细节。


下面是AC代码:

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 505;
const int INF = (1<<30)-1;
int g[maxn][maxn];
int lx[maxn],ly[maxn];
int match[maxn];
bool visx[maxn],visy[maxn];
int slack[maxn];
int n,m;
bool dfs(int cur){
     visx[cur] = true;
     for(int y=1;y<=m;y++){
         if(visy[y])   continue;
//         if(g[cur][y]==INF)  continue;
         int t=lx[cur]+ly[y]-g[cur][y];
         if(t==0){
            visy[y] = true;
            if(match[y]==-1||dfs(match[y])){
                match[y] = cur;
                return true;
            }
         }
         else if(slack[y]>t){
                 slack[y]=t;
         }
     }
     return false;
}
int KM(){
    memset(match,-1,sizeof(match));
    memset(ly,0,sizeof(ly));
    for(int i=1 ;i<=n;i++){
         lx[i]=-INF;
       for(int j=1;j<=m;j++)
           if(g[i][j]>lx[i])   lx[i]=g[i][j];
   }
   for(int x=1;x<=n;x++){
        for(int i=1;i<=m;i++)  slack[i]=INF;
        while(true){
            memset(visx,false,sizeof(visx));
            memset(visy,false,sizeof(visy));
            if(dfs(x))  break;
            int d=INF;
            for(int i=1;i<=m;i++){
               if(!visy[i]&&d>slack[i])     d=slack[i];
            }
            for(int i=1;i<=n;i++){
               if(visx[i])                  lx[i]-=d;
            }
            for(int i=1;i<=m;i++){
               if(visy[i])                 ly[i]+=d;
               else                        slack[i]-=d;
            }
        }
   }
    int result = 0,flag=0;
    for(int i = 1; i <=m; i++){
        if(match[i]==-1||g[match[i]][i]==-INF)
            continue;
      if(match[i]>-1){
        result += g[match[i]][i];
        flag++;
      }
    }
    if(flag<n) result=-1;
    return result;
}
int main(){
    int a,b,c,e,ca=1;
    while(scanf("%d%d%d",&n,&m,&e)!=EOF){
        memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++)
         for(int j=1;j<=m;j++)
             g[i][j]=-INF;
        for(int i=0;i<e;i++) {
            scanf("%d%d%d",&a,&b,&c);
            a++;     b++;
            if(c<0)  continue;            //没这句话会跪。
            g[a][b]=c;
        }

        int ans=KM();
        printf("Case %d: %d\n",ca++,ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值