hdu1045 Fire Net

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

二分图匹配,匈牙利算法(dfs+邻接矩阵),König定理

需要自己建新图

以前用搜索做过~ 感觉建图好神奇

 

 1 #include <stdio.h>
 2 #include <string.h>
 3 #define N 10
 4 
 5 int n, m;
 6 int map0[N][N], map1[N][N], map2[N][N];
 7 int map[N][N], girl[N], flag[N];
 8 
 9 int find(int x)
10 {
11     int i;
12     for(i=1; i<=m; i++)
13     {
14         if(!flag[i] && map[x][i])
15         {
16             flag[i] = 1;
17             if(girl[i]==-1 || find(girl[i]))
18             {
19                 girl[i] = x;
20                 return 1;
21             }
22         }
23     }
24     return 0;
25 }
26 
27 int main()
28 {
29     int n0, i, j, sum, count;
30     char c;
31     while(scanf("%d%*c", &n0), n0)
32     {
33         //初始化
34         memset(map, 0, sizeof(map));
35         memset(girl, -1, sizeof(girl));
36         for(i=1; i<=n0; i++)
37         {
38             map0[i][0] = map0[0][i] = 1;
39             for(j=1; j<=n0; j++)
40             {
41                 scanf("%c", &c);
42                 map0[i][j] = c-'.';
43             }
44             getchar();
45         }
46         //给每个点编一个新行号
47         count = 0;
48         for(i=1; i<=n0; i++)
49         {
50             for(j=1; j<=n0; j++)
51             {
52                 if(map0[i][j-1] && (!map0[i][j]))
53                 {
54                     count ++;
55                 }
56                 map1[i][j] = count;
57             }
58         }
59         n = count;
60         //给每个点编一个新列号
61         count = 0;
62         for(j=1; j<=n0; j++)
63         {
64             for(i=1; i<=n0; i++)
65             {
66                 if(map0[i-1][j] && (!map0[i][j]))
67                 {
68                     count ++;
69                 }
70                 map2[i][j] = count;
71             }
72         }
73         m = count;
74         //根据新的行列号,建图
75         for(i=1; i<=n0; i++)
76         {
77             for(j=1; j<=n0; j++)
78             {
79                 if(!map0[i][j])
80                 {
81                     map[map1[i][j]] [map2[i][j]] = 1;
82                 }
83             }
84         }
85         //匈牙利算法
86         sum = 0;
87         for(i=1; i<=n; i++)
88         {
89             memset(flag, 0, sizeof(flag));
90             sum += find(i);
91         }
92         printf("%d\n", sum);        
93     }
94     return 0;
95 }

 

 

posted @ 2012-12-22 19:41  Yuan1991  阅读(133)  评论(0编辑  收藏  举报