E-room (km) 带权二分图

链接:https://www.nowcoder.com/acm/contest/143/E
来源:牛客网
 

题目描述

Nowcoder University has 4n students and n dormitories ( Four students per dormitory). Students numbered from 1 to 4n.

And in the first year, the i-th dormitory 's students are (x1[i],x2[i],x3[i],x4[i]), now in the second year, Students need to decide who to live with.

In the second year, you get n tables such as (y1,y2,y3,y4) denote these four students want to live together.

Now you need to decide which dormitory everyone lives in to minimize the number of students who change dormitory.

输入描述:

The first line has one integer n.

Then there are n lines, each line has four integers (x1,x2,x3,x4) denote these four students live together in the first year

Then there are n lines, each line has four integers (y1,y2,y3,y4) denote these four students want to live together in the second year

输出描述:

Output the least number of students need to change dormitory.

示例1

输入

2
1 2 3 4
5 6 7 8
4 6 7 8
1 2 3 5

输出

2

说明

Just swap 4 and 5

备注:

1<=n<=100

1<=x1,x2,x3,x4,y1,y2,y3,y4<=4n

It's guaranteed that no student will live in more than one dormitories.

思路:每组X都与每组Y对应建立边权,边权保存不需要换寝的人数,跑一个带权最大二分图匹配,然后总人数减去匹配人数即可。

代码:

#include
using namespace std;
const int N=205;
int n;
int g1[N][5],g2[N][5],g3[N][N],d;
int match[N];
int x[N],y[N];
int vx[N],vy[N];

bool dfs(int s){
    vx[s]=1;
    for(int j=1;j<=n;j++){
        if(vy[j]) continue;
        int tem=x[s]+y[j]-g3[s][j];
        if(tem==0) {
            vy[j]=1;
            if(match[j]==-1||dfs(match[j])){
                match[j]=s;
                return true;
            }
        }
        else if(tem>0) d=min(d,tem);
    }
    return false;
}


void km(){
    for(int i=1;i<=n;i++){
        match[i]=-1;
        x[i]=y[i]=0;
        for(int j=1;j<=n;j++) x[i]=max(g3[i][j],x[i]);
    }
    for(int i=1;i<=n;i++){
        while(1){
            d=0x3f3f3f3f3f;
            memset(vx,0,sizeof(vx));
            memset(vy,0,sizeof(vy));
            if(dfs(i)) break;
            for(int j=1;j<=n;j++){
                if(vy[j]) y[j]+=d;
                if(vx[j]) x[j]-=d;
            }
        }
    }

    int ans=0;
    for(int i=1;i<=n;i++) ans+=g3[match[i]][i];
    printf("%d\n",4*n-ans);
}

int main(){
        while(~scanf("%d",&n)){
                for(int i=1;i<=n;i++){
                    for(int j=1;j<=4;j++) scanf("%d",&g1[i][j]);
                }
                for(int i=1;i<=n;i++){
                    for(int j=1;j<=4;j++) scanf("%d",&g2[i][j]);
                }

                for(int i=1;i<=n;i++){///½¨Í¼
                    for(int  j=1;j<=n;j++) {
                        int tem=0;
                        for(int  ii=1;ii<=4;ii++){
                            for(int jj=1;jj<=4;jj++) if(g1[i][ii]==g2[j][jj]) tem++;
                        }
                        g3[i][j]=tem;
                    }
                }
                km();
        }
}

 

你可能感兴趣的:(KM,KM)