Maximum Independent Set

This case is an implements of Hungarian Algorithm.The module of the problem is maximum independent number = vertexs - maximum matching.

Background

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.

Implements

Attention:The bond is bidirectional and the maximum matching number = 1/2 relations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Title:Hungarian Algorithm
// Author:Call偶围城
#include <stdio.h>
#define MAX 1005
int N;
int stu[MAX];
int bond[MAX][MAX];
int matching[MAX];
int find(int stuNo) {
int i;
for (i = 0;i < N;i++) {
if (bond[stuNo][i] == 1 && matching[i] == -1){
matching[i] = 1;
if (stu[i] == -1 || find(stu[i]) == 1) {
stu[i] = stuNo;
return 1;
}
}
}
return 0;
}
int main() {
int cnt;
int i, j, k, n;
while (scanf("%d", &N) != EOF) {
cnt = 0;
for (i = 0;i < MAX;i++) {
stu[i] = -1;
for (j = 0;j < MAX;j++)
bond[i][j] = -1;
}
for (i = 0;i < N;i++) {
scanf("%d: (%d)", &j, &n);
while (n--) {
scanf("%d", &k);
bond[j][k] = 1;
bond[k][j] = 1;
}
}
for (i = 0;i < N;i++)
for (j = 0;j < N;j++)
for (i = 0;i < N;i++) {
for (j = 0;j < N;j++) {
matching[j] = -1;
}
if (find(i) == 1) {
cnt++;
}
}
printf("%d\n", N-cnt/2);
}
return 0;
}

Samples

Inputs:
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

Outputs:
5
2

Source

http://acm.hdu.edu.cn/showproblem.php?pid=1068