您的位置:首页 > 其它

Farm Irrigation(并查集)

2013-10-07 18:25 246 查看
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4479 Accepted Submission(s): 1942


[align=left]Problem Description[/align]
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.

#include<stdio.h>
#include<string.h>
const int N = 100;
int n,m;
char map

;
int set[N*N];
int pipe[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 < n*m; i++)
set[i] = i;
}

int find(int x)
{
if(set[x] != x)
set[x] = find(set[x]);
return set[x];
}

int judge(char a, char b, int pos)
{
int x = a-'A';
int y = b-'A';

if(pos)
{
if(pipe[x][2] == 1 && pipe[y][0] == 1)
return 1;
else return 0;
}
else
{
if(pipe[x][1] == 1 && pipe[y][3] == 1)
return 1;
else return 0;
}
}

void merge(int a,int b)
{
a = find(a);
b = find(b);
set[a] = b;
}

int main()
{
int i,j;
while(~scanf("%d %d",&n,&m))
{
if(n == -1 && m == -1)
break;
getchar();
init();
for(i = 0; i < n; i++)
gets(map[i]);

for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(i != n-1)
{
if(judge(map[i][j],map[i+1][j],1))//1表示两个字母所代表的管子位置关系是上下;
{
merge(i*m+j,(i+1)*m+j);
}
}
if(j != m-1)
{
if(judge(map[i][j],map[i][j+1],0))//0表示两个字母所代表的管子位置关系是左右;
{
merge(i*m+j,i*m+j+1);
}
}
}
}
int count = 0;
for(i = 0; i < n*m; i++)
{
if(set[i] == i)
count++;
}
printf("%d\n",count);

}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: