【hdu1198】Farm Irrigation——并查集

来源:互联网 发布:linux 查看系统时区 编辑:程序博客网 时间:2024/06/01 09:04

Problem Description
Benny has a spacious farm land to irrigate. The farm land is a rectangle, and is divided into a lot of samll squares. Water pipes are placed in these squares. Different square has a different type of pipe. There are 11 types of pipes, which is marked from A to K, as Figure 1 shows.


Figure 1


Benny has a map of his farm, which is an array of marks denoting the distribution of water pipes over the whole farm. For example, if he has a map 

ADC
FJK
IHE

then the water pipes are distributed like 


Figure 2


Several wellsprings are found in the center of some squares, so water can flow along the pipes from one square to another. If water flow crosses one square, the whole farm land in this square is irrigated and will have a good harvest in autumn. 

Now Benny wants to know at least how many wellsprings should be found to have the whole farm land irrigated. Can you help him? 

Note: In the above example, at least 3 wellsprings are needed, as those red points in Figure 2 show.
 

Input
There are several test cases! In each test case, the first line contains 2 integers M and N, then M lines follow. In each of these lines, there are N characters, in the range of 'A' to 'K', denoting the type of water pipe over the corresponding square. A negative M or N denotes the end of input, else you can assume 1 <= M, N <= 50.
 

Output
For each test case, output in one line the least number of wellsprings needed.
 

Sample Input
2 2DKHF3 3ADCFJKIHE-1 -1
 

Sample Output
23


        题意:给定是一张标准图,四条边要么可以与其他边相连要么不能,给定他们的排列,求联通的图块的个数。


        这道题很简单,判断第i张的图与它右边和下边的图是否联通就行了,如果联通那么就合并,最后数关键元素有多少就好。

        但是今天听讲正好学了有关二进制运算的东西,恰好这个图要么通要么不通,如果通的话就是1不通就是0,如果两个点都是通才能联通,这是与运算,所以在实现的时候用二进制来表示通或者不通。

#include <iostream>#include <algorithm>#include <cstring>using namespace std;const int maxn = 2505;const int pic[11][4] = { {1,1,0,0},{0,1,1,0},{1,0,0,1},{0,0,1,1},{0,1,0,1},{1,0,1,0},{1,1,1,0},{1,1,0,1},{1,0,1,1},{0,1,1,1},{1,1,1,1} };int fa[maxn], deep[maxn];void init(int size){for (int i = 0; i < maxn; i++){fa[i] = i;deep[i] = 0;}}int find(int x){if (fa[x] == x)return x;return fa[x] = find(fa[x]);}void unite(int x, int y){x = find(x);y = find(y);if (x == y)return;if (deep[x] < deep[y])fa[x] = y;else{fa[y] = x;if (deep[x] = deep[y])deep[x]++;}}bool same(int x, int y){return find(x) == find(y);}int main(){//freopen("input.txt", "r", stdin);int m, n;char s[55][55]={ 0 };while (scanf("%d%d", &m, &n), m >= 0 || n >= 0){init(m*n);for (int i = 0; i < m; i++)scanf("%s", s[i]);for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){if (pic[s[i][j] - 'A'][2] && pic[s[i][j + 1] - 'A'][0] && j!=n-1)unite(i*n + j, i*n + j + 1);if (pic[s[i][j] - 'A'][3] && pic[s[i + 1][j] - 'A'][1] && i!=m-1)unite(i*n + j, (i + 1)*n + j);}}int num = 0;for (int i = 0; i < n*m; i++)if (i == fa[i])num++;cout << num << endl;}return 0;}


0 0