Description
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
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
Output
Sample Input
2 2 DK HF 3 3 ADC FJK IHE -1 -1
Sample Output
2 3
作为一名合格的菜鸟,这道题真是让我想了各种和并查集的关系,最后忍不住从网上查了代码,所以为了让自己
铭记这个题,我要详细把这道题走一遍以解心头之恨,哈哈
其实这道题很简单,之所以没做出来,从很大一方面是被题给吓着了,因为之前很少做这种有图的(菜鸟就这水平了)
仔细看这套代码,发现自己真的笨。
像并查集类的题,无非就是判断在不在同一个集合,判断在不在一个集合,就要首先建立集合的模型,如果凭空给你一个这种题
你或许会暂时在思路上有些犹豫,但是这个题已经知道是并查集的了,那么我们有了思考的方向,也会并查集了,应该难度不大了
这里的集合就是联通的水管,一旦上下左右联通了,那么就把它们放进一个集合里,在这里用并查集,我们知道,在并查集
里必须有且只有一个根,那么这个跟有什么作用呢,他可以将所有的除自己的子集的数组改变值,这样只有跟的值会保持
不变,找出集合的数量,也就是根的数量:
我觉得最好解释代码的方法,就是将变量的含义表示出来,这样读者既可以自己走一遍,也可以衍生出新的方法和有效地
剪枝方向:
state: 表示水管的性质;
红色部分:从第0行第1列开始遍历
遍历后将值处理,演变成简单并查集的题最后找有多少个集合就行了。
#include<set>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 55;
const int MAXN = 10000;
int n , m;
int father[MAXN];
char mat[N][N];
int state[11][4] =
{{1,0,0,1},{1,1,0,0},{0,0,1,1},{0,1,1,0},{1,0,1,0},{0,1,0,1},
{1,1,0,1},{1,0,1,1},{0,1,1,1},{1,1,1,0},{1,1,1,1}};
void init(){
for(int i = 0 ; i < MAXN ; i++)
father[i] = i;
}
int find(int x){
if(father[x] != x)
father[x] = find(father[x]);
return father[x];
}
void Union(int x , int y){
int fx = find(x);
int fy = find(y);
father[fx] = fy;
}
void output(){
set<int> s;
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < m ; j++)
s.insert(find(i*m+j));
printf("%d\n" , s.size());
}
int main(){
char ch;
while(scanf("%d%d%*c" , &n , &m) && n > 0){
init();
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
scanf("%c" , &mat[i][j]);
ch = mat[i][j];
int x = ch-'A';
if(i && state[x][0] == 1){
int y = mat[i-1][j]-'A';
if(state[x][0] == state[y][2])
Union(i*m+j , (i-1)*m+j);
}
if(j && state[x][3] == 1){
int y = mat[i][j-1]-'A';
if(state[x][3] == state[y][1])
Union(i*m+j , i*m+j-1);
}
}
getchar();
}
output();
}
return 0;
}