KM 二分图匹配

#include
using namespace std;

const int MAXN = 505;
const int INF = 0x3f3f3f3f;
 
int N;
int a[MAXN][MAXN];
int ex_X[MAXN],ex_Y[MAXN];
int match[MAXN],slack[MAXN];
bool visX[MAXN],visY[MAXN];
 
inline bool dfs(int x , int flag){
    
    visX[x] = true;
    for(int i = 0;i<N;++i){
        if(visY[i])  continue;
        int temp = ex_X[x] + ex_Y[i] - a[x][i];
        if(temp==0){
            visY[i] = true;
            if(match[i]==-1 || dfs(match[i],flag)){
                if(flag)    match[i] = x;
                return true;
            }
        }
        else
            slack[i] = min( slack[i] , temp );
    }
    return false;
}
 
long long km(){
    memset(match , -1 , sizeof(match));
    memset(ex_Y , 0 , sizeof(ex_Y));
    for(int i = 0;i<N;++i){
        ex_X[i] = a[i][0];
        for(int j = 1;j<N;++j){
            ex_X[i] = max(ex_X[i],a[i][j]);
        }
    }
    
    for(int i = 0;i<N;++i){
        
        memset(visY, false, sizeof(visY));
        memset(visX, false, sizeof(visX));
        for(int j = 0;j<N;++j)  slack[j] = INF;
        
        if(dfs(i,1))    continue;
        
        bool isOK = true;
        
        while(isOK){
        
            int tempDelta = INF;
            for(int i = 0;i<N;++i){
                if(!visY[i] && tempDelta > slack[i])
                    tempDelta =  slack[i] ;
            }
            
            for(int i = 0;i<N;++i){
                if(visX[i])
                    ex_X[i] -= tempDelta;
                
                if(visY[i])
                    ex_Y[i] += tempDelta;
                else
                    slack[i] -= tempDelta;
            }
            
            for(int i = 0;i<N;++i){
                
                if(!visY[i] && slack[i]==0){
                    
                    visY[i] = true;
                    if(match[i]==-1 || dfs(match[i],0)){
                        isOK = false;
                        break;
                    }
                }
            }
            
        }
        
        memset(visY, false, sizeof(visY));
        memset(visX, false, sizeof(visX));
        dfs(i,1);
    }
    
    long long res = 0;
    for(int i = 0;i<N;i++)
        res += a[match[i]][i];
    
    return res;
}
 
int main(){
    int T;
    scanf("%d",&T);
    int tt = T;
    while(tt--){
        
        scanf("%d",&N);
        for(int i = 0;i<N;i++){
            for(int j = 0;j<N;j++){
                scanf("%d",&a[i][j]);
                a[i][j]*=-1;//这个km是最小费用,如果要求最大*-1就好 
            }
        }
        printf("Case #%d: %lld\n",T-tt,-km());
        
    }
}

你可能感兴趣的:(代码模板)