Farm IrrigationTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11674 Accepted Submission(s): 5048 Problem Description 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 2 DK HF 3 3 ADC FJK IHE -1 -1 Sample Output 2 3 Author ZHENG, Lu Source |
【题意】
类似小时候玩的管道游戏嘿嘿嘿。给9种管子的形态,能够互相连通的算是一个连通分量,计算图中共有多少个连通分量。
【解题思路】
用edge数组保存每个水管上下左右四个方向是否连通,连通即是1,否则即是0,如果两根水管在水平或竖直方向连通总用并查集将两根水管连接起来(需要将二维数组转换成一维比较方便),然后计算连通分量个数即可。
【代码】
#include<bits/stdc++.h>
using namespace std;
const int maxn=550;
char a[maxn][maxn];
int pre[maxn*maxn+1],num,n,m;
int edge[11][4]={{1,0,1,0},{1,0,0,1},{0,1,1,0},{0,1,0,1},
{1,1,0,0},{0,0,1,1},{1,0,1,1},{1,1,1,0},
{0,1,1,1},{1,1,0,1},{1,1,1,1}};
void init()
{
for(int i=0;i<n*m;i++)
pre[i]=i;
num=n*m;
}
int findroot(int x)
{
int r=x;
while(r!=pre[r])
r=pre[r];
return r;
}
void add(int x1,int y1,int x2,int y2,int t)
{
if(x2>=n || y2>=m)return;
int flag=0;
int ta=a[x1][y1]-'A';
int tb=a[x2][y2]-'A';
if(t)
{
if(edge[ta][1] && edge[tb][0])flag=1;
}
else
{
if(edge[ta][3] && edge[tb][2])flag=1;
}
if(flag)
{
int fx=findroot(x1*m+y1);
int fy=findroot(x2*m+y2);
if(fx!=fy)
{
pre[fx]=fy;
num--;
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m) && n!=-1 ||m!=-1)
{
for(int i=0;i<n;i++)
scanf("%s",a[i]);
init();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
add(i,j,i+1,j,1);
add(i,j,i,j+1,0);
}
}
printf("%d\n",num);
}
return 0;
}