[hdu2255] Ben Xiaokang makes a lot of money (optimal matching of bipartite graph, KM algorithm)

The main idea of ​​the title: Find the optimal matching of the bipartite graph (the largest number first, followed by the largest weight).

The key to solving the problem: KM algorithm

Complexity: $O(n^3)$

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<cmath>
using namespace std;
typedef long  long ll;
 const  int N= 310 ;
 const  int inf= 0x3f3f3f3f ;
 int nx,ny;
 int g[N][N];
 int match[N],lx[N],ly[N]; // y The matching state of each point in the , the vertex label in x, y 
int slack[N];
 bool visx[N],visy[N];

bool hungry(int x){
    visx[x]=1;
    for(int y=1; y<=ny; y++){
        if(visy[y])continue;
        int tmp=lx[x]+ly[y]-g[x][y];
        if(tmp==0){
            visy[y]=true;
            if(match[y]==-1 ||hungry(match[y])){
                match[y]=x;
                return 1;
            }
        }
        else if(slack[y]>tmp) slack[y]=tmp;
    }
    return 0;
}

int KM () {
    memset(match, -1, sizeof match);
    memset(ly, 0, sizeof ly);
    for(int i=1;i<=nx;i++){
        lx[i]=-inf;
        for(int j=1;j<=ny;j++) lx[i]=max(lx[i],g[i][j]);
    }
    for(int x=1;x<=nx;x++){
        for(int i=1;i<=ny;i++) slack[i]=inf;
        while(1){
            memset(visx,0,sizeof visx);
            memset(visy,0,sizeof visy);
            if(hungry(x))break;
            int d=inf;
            for(int i=1;i<=ny;i++)if(!visy[i]&&d>slack[i]) d=slack[i];
            for(int i=1;i<=nx;i++)if(visx[i])lx[i]-=d;
            for(int i=1;i<=ny;i++){
                if(visy[i])ly[i]+=d;
                else slack[i]-=d;
            }
        }
    }
    int res=0;
    for(int i=1;i<=ny;i++)
        if(match[i]!=-1) res+=g[match[i]][i];
    return res;
}

int main(){
    int n;
    while(~scanf("%d",&n)){
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&g[i][j]);
        nx = ny = n;
        printf("%d\n",KM());
    }
    return 0;
}
 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325081113&siteId=291194637