Farm Irrigation
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 46 Accepted Submission(s) : 26
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> using namespace std;
char map[][];
int par[];
int find(int x)
{
while(x!=par[x])
x=par[x];
return x;
}
void unioni(int x,int y)
{
int xx=find(x);
int yy=find(y);
if(xx!=yy)
{
par[yy]=xx;
} }
int main()
{
int n,m;
while(cin>>n>>m)
{
if(n<||m<)
break;
for(int i=;i<n*m;i++)
par[i]=i;
for(int i=;i<n;i++)
for(int j=;j<m;j++)
{
cin>>map[i][j];
} for(int i=;i<n;i++)
for(int j=;j<m;j++)
{
if(i>=&&(map[i][j]=='A'||map[i][j]=='B'||map[i][j]=='E'||map[i][j]=='G'||map[i][j]=='H'||map[i][j]=='J'||map[i][j]=='K'))
{
if(map[i-][j]=='C'||map[i-][j]=='D'||map[i-][j]=='E'||map[i-][j]=='H'||map[i-][j]=='I'||map[i-][j]=='J'||map[i-][j]=='K')
{
unioni((i-)*m+j,i*m+j);
}
}
if(j>=&&(map[i][j]=='A'||map[i][j]=='C'||map[i][j]=='F'||map[i][j]=='G'||map[i][j]=='H'||map[i][j]=='I'||map[i][j]=='K'))
if(map[i][j-]=='B'||map[i][j-]=='D'||map[i][j-]=='F'||map[i][j-]=='G'||map[i][j-]=='I'||map[i][j-]=='J'||map[i][j-]=='K')
{
unioni(i*m+j-,i*m+j);
}
}
int flag=;
for(int i=;i<n*m;i++)
{
if(par[i]==i)
flag++; }
cout<<flag<<endl; }
return ;
}