Kuhn-Munkres algorithm template (maximum weight matching of bipartite graph)

Explain https://blog.csdn.net/thundermrbird/article/details/52231639

Code https://blog.csdn.net/pi9nc/article/details/12250247

int n;
int weight[MAX][MAX];
int boy[MAX];
bool sx[MAX],sy[MAX];
bool max_match(int gg)
{
    sx[gg]=true;
    for(int i=0;i<n;i++)
    {
        if(!sy[i]&&lx[gg]+ly[i]==weight[gg][i])
        {
           and [i] = true;
            if(boy[i]==-1||max_match(i))
            {
                boy[i]=gg;
                return true;
            }
        }
    }
    return false;
    
}
void KM(int sign)
{
    if(sign)
    {
        for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
              weight[i][j]=-weight[i][j];
    }
    memset(boy,-1,sizeof(boy));
    for(int i=0;i<n;i++)
    {
        ly[i]=0;
        lx[i]=-INF;
        for(int j=0;j<n;j++)
        {
            if(weight[i][j]>lx[i])
            {
                lx[i]=weight[i][j];
            }
        }
    }
    for(int i=0;i<n;i++)
    {
        while(1)
        {
            memset (sy, 0, sizeof (sy));
            memset(sx,0,sizeof(sx));
            if(max_match(i)) break;
            int d=INF;
            for(int j=0;j<n;j++)
            {
                if(sx[j])
                {
                    for(int k=0;k<n;k++)
                    {
                        if(sy[k]&&(lx[j]+ly[k]-weight[j][k])<d)
                        {
                            d=lx[j]+ly[k]-weight[j][k];
                        }
                    }
                }
            }
            if(d==0) return -1;
            for(int f=0;f<n;f++)
            {
                if(sx[f])
                lx[f]-=d;
                if (sy [f])
                ly[f]+=d;
            }
        }
    }
    int sum=0;
    for(int i=0;i<n;i++)
    {
        if(boy[i]>=0)
        {
            sum+=weight[boy[i]][i];
        }
    }
    if(sign) sum=-sum;
    return sum;
}

Guess you like

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