`
Simone_chou
  • 浏览: 185409 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

Girls and Boys(二分图最大匹配 + 匈牙利算法)

    博客分类:
  • HDOJ
 
阅读更多

Girls and Boys

Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6595    Accepted Submission(s): 2976


Problem Description
the second year of the university somebody started a study on the romantic relations between the students. The relation “romantically involved” is defined between one girl and one boy. For the study reasons it is necessary to find out the maximum set satisfying the condition: there are no two students in the set who have been “romantically involved”. The result of the program is the number of students in such a set.

The input contains several data sets in text format. Each data set represents one set of subjects of the study, with the following description:

the number of students
the description of each student, in the following format
student_identifier:(number_of_romantic_relations) student_identifier1 student_identifier2 student_identifier3 ...
or
student_identifier:(0)

The student_identifier is an integer number between 0 and n-1, for n subjects.
For each given data set, the program should write to standard output a line containing the result.
 

 

Sample Input
7
0: (3) 4 5 6
1: (2) 4 6
2: (0)
3: (0)
4: (2) 0 1
5: (1) 0
6: (2) 0 1
 
 
3
0: (2) 1 2
1: (1) 0
2: (1) 0
 

 

Sample Output

 

5
2

 

    题意:

    给出 N(<= 500)有 N 个同学 ,给出每个同学自己所中意的人,求一个最大集合,这个集合里面的人相互之间没有任何喜欢的关系。

 

    思路:

    二分图最大匹配。匈牙利算法。求最大独立集,最大独立集 = 结点数 - 最大匹配数。每个点都匹配一次的话,最终结果要除以2,因为这是无向图。

 

    AC:

#include <cstdio>
#include <string.h>
using namespace std;

int n;
int w[505][505],vis[505],linker[505];

bool dfs(int u) {
    for(int v = 0;v < n;v++)
        if(w[u][v] && !vis[v]) {
            vis[v] = 1;
            if(linker[v] == -1 || dfs(linker[v])) {
                linker[v] = u;
                return true;
            }
        }

    return false;
}

int hungary() {
    int res = 0;
    memset(linker,-1,sizeof(linker));
    for(int u = 0;u < n;u++) {
        memset(vis,0,sizeof(vis));
        if(dfs(u)) res++;
    }

    return res;
}

int main() {
    while(~scanf("%d",&n)) {
        memset(w,0,sizeof(w));
        for(int i = 0;i < n;i++) {
            int num,ans;
            scanf("%d: (%d)",&num,&ans);
            while(ans--) {
                scanf("%d",&num);
                w[i][num] = 1;
            }
        }

        printf("%d\n",n - hungary() / 2);
    }
    return 0;
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics