1. 程式人生 > >E-room (km) 帶權二分圖

E-room (km) 帶權二分圖

題目描述

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<bits/stdc++.h>
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();
        }
}