并查集:
行中有哪些图能够连接,列中有哪些图能够连接,分别记录他们,
这样就构成一个并查集的模型,每次把输入的数据遍历,用并查集记录他们
最后再找几个最高父节点;
#include <stdio.h>
#include <string.h>
int up[8],down[8],left[8],right[8];
int f[2550];
char map[55][55];
char ud[100][100], lr[100][100];
void pd()
{
up[0] = 'A';
up[1] = 'B';
up[2] = 'E';
up[3] = 'G';
up[4] = 'H';
up[5] = 'J';
up[6] = 'K';
down[0] = 'C';
down[1] = 'D';
down[2] = 'E';
down[3] = 'H';
down[4] = 'I';
down[5] = 'J';
down[6] = 'K';
left[0] = 'A';
left[1] = 'C';
left[2] = 'F';
left[3] = 'G';
left[4] = 'H';
left[5] = 'I';
left[6] = 'K';
right[0] = 'B';
right[1] = 'D';
right[2] = 'F';
right[3] = 'G';
right[4] = 'I';
right[5] = 'J';
right[6] = 'K';
memset(ud, 0, sizeof(ud));
memset(lr, 0, sizeof(lr));
for(int i = 0; i <= 6; i++)
for(int j = 0; j <= 6; j++)
{
ud[down[i]][up[j]] = 1;
lr[right[i]][left[j]] = 1;
}
}
int find_fa(int x)
{
if(x != f[x]) f[x] = find_fa(f[x]);
return f[x];
}
void set_(int x, int y)
{
x = find_fa(x);
y = find_fa(y);
if(x != y) f[x] = y;
}
int main()
{
pd();
int m, n;
while(scanf("%d%d", &m, &n) != EOF)
{
if(m == -1 && n == -1) break;
for(int i = 0; i <= m*n; i++) f[i] = i;
for(int i = 0; i < m; i++) scanf("%s", map[i]);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(j < n-1 && lr[map[i][j]][map[i][j+1]] == 1)
{
int t1 = i*n + j;
int t2 = i*n + j + 1;
set_(t1, t2);
}
if(i < m-1 && ud[map[i][j]][map[i+1][j]] == 1)
{
int t1 = i*n + j;
int t2 = (i+1)*n + j;
set_(t1, t2);
}
}
}
int k = 0;
for(int i = 0; i < m*n; i++)
if(f[i] == i) k++;
printf("%d\n", k);
}
}
hdu1198并查集
最新推荐文章于 2018-08-16 21:09:38 发布