Farm Irrigation
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 38 Accepted Submission(s) : 24
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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
Output
Sample Input
2 2
DK
HF 3 3
ADC
FJK
IHE -1 -1
Sample Output
2
3
Author
Source
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<set>
using namespace std;
int mp[]={,,,,,,,,,,};
//表示一种状态,B(1<<0)+(1<<1)=3:表示上右是通的.
int dr[][]={{-,},{,},{,},{,-} };// 上,右,下,左
int n,m;
char ch[][];
int fa[*];
bool ok(int x,int y)
{
if (x< || x>=n) return ;
if (y< || y>=m) return ;
return ;
}
int findfa(int k)
{
if (fa[k]==k) return k;
else return fa[k]=findfa(fa[k]);
}
int main()
{ while(~scanf("%d%d",&n,&m))
{
if (n< || m<) break;
for(int i=;i<n;i++)
scanf("%s",&ch[i]); for(int i=;i<n*m;i++) fa[i]=i; for(int i=;i<n;i++)
for(int j=;j<m;j++)
{
for(int k=;k<;k++) //向右,向下两个方向
{
int x=i+dr[k][];
int y=j+dr[k][];
if (!ok(x,y)) continue;
if ( (mp[ch[i][j]-'A']&(<<k))== || (mp[ch[x][y]-'A']&(<<((k+)%)))== ) continue;
int fx=findfa(i*m+j); //之前一直错,问题在这里应该是*m而不是n。
int fy=findfa(x*m+y);
if (fx!=fy) fa[fx]=fy;
} } int sum=;
for(int i=;i<n*m;i++) if (fa[i]==i) sum++;
printf("%d\n",sum);
}
return ;
}