Shirlies
宁静专注认真的程序媛~

一看到这一题,我真没想到用并查集做,坑啊,看看别人的大致思路才知道用并查集可以做,唉,看来是自己太弱了~~~

View Code
 1 #include <cstdio>
2 #include <cstring>
3
4 int pipe[11][4]={{1,0,0,1},{1,1,0,0},{0,0,1,1},
5 {0,1,1,0},{1,0,1,0},{0,1,0,1},{1,1,0,1},{1,0,1,1},
6 {0,1,1,1},{1,1,1,0},{1,1,1,1}};//将每个都编号了,并且用上了边
7 int f[3000];
8 int map[3000];
9
10 int find(int x)
11 {
12 if(x == f[x])
13 return x;
14 int t = find(f[x]);
15 f[x] = t;
16 return t;
17 }
18
19 void join(int x,int y)
20 {
21 int fx = find(x);
22 int fy = find(y);
23 if(fx != fy)
24 f[fx] = fy;
25 }
26
27 int main()
28 {
29 int n,m;
30 while(scanf("%d%d",&n,&m) == 2)
31 {
32 if(n < 0||m < 0)
33 break;
34 char ch;
35 getchar();
36 int i,j;
37 int k = 0,num;
38 for(i = 0;i < n;i ++)
39 {
40 for(j = 0;j < m;j ++)
41 {
42 scanf("%c",&ch);
43 num = ch - 'A';
44 map[k ++] = num;//将字母数字化,并按顺序记录
45 }
46 getchar();
47 }
48
49 for(i = 0;i < k;i ++)
50 {
51 f[i] = i;
52 }
53
54 int ins;
55 for(i = 0;i < k;i ++)
56 {
57 int row = i / m;//将数字化的结果还得转化为行列,这样方便判断它上下左右
58 int col = i - row * m;
59
60 if(row-1 >= 0)
61 {
62 ins = i - m;
63 if(pipe[map[ins]][2]&&pipe[map[i]][0])
64 join(ins,i);
65 }
66 if(col + 1 < m)
67 {
68 ins = i + 1;
69 if(pipe[map[ins]][3]&&pipe[map[i]][1])
70 join(ins,i);
71 }
72 if(row + 1 < n)
73 {
74 ins = i + m;
75 if(pipe[map[ins]][0]&&pipe[map[i]][2])
76 join(ins,i);
77 }
78 if(col - 1 >= 0)
79 {
80 ins = i - 1;
81 if(pipe[map[ins]][1]&&pipe[map[i]][3])
82 join(ins,i);
83 }
84 }
85 int ans = 0;
86 for(i = 0;i < k;i ++)
87 {
88 if(f[i] == i)
89 ans ++;
90 }
91 printf("%d\n",ans);
92 }
93 return 0;
94 }

 

posted on 2012-03-10 00:02  Shirlies  阅读(461)  评论(0编辑  收藏  举报