## hihocoder #1487 岛屿3 并查集+搜索

### 描述

H国正在进行一项持续N周的填海造岛工程。整片工程海域可以被看作是1000x1000的网格。

``````#..
...
...
``````

``````#..
.#.
...
``````

``````#..
##.
...
``````

### 输出

``````3
0 0
1 1
1 0``````

``````1 1 4
2 2 8
1 3 8 ``````

``````import java.util.Scanner;

public class hihocoder_1487_岛屿3 {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
f = new int[1005*1005+5];
for(int i=0;i<=1005*1005;i++)
f[i] = -1;//初始化海
for(int i=1;i<=n;i++) {
int a = 1005*in.nextInt()+in.nextInt();
f[a] = a;
insert(a, i);
}

}

static int n;
static int[] f;
static int cnt=0,c=0;

static int find(int x) {
if(f[x]==x)//x = 1005*x+y
return x;
return f[x] = find(f[x]);
}

static void insert(int x,int m) {
cnt++;
int k=0;
k+=union(x,x-1005);
k+=union(x,x+1);
k+=union(x,x+1005);
k+=union(x,x-1);
c+=4-2*k;
System.out.println(cnt+" "+m+" "+c);
}

static int union(int x,int y) {
if(y<0 || y>1005*1005 || f[y]==-1)
return 0;
int u = find(f[x]);
int v = find(f[y]);
//		System.out.println(x+" "+y);
if(u!=v) {
f[u] = v;
cnt--;
}
return 1;
}

}``````

0条评论