# Counting Islands II_太阁竞赛C

Country H is going to carry out a huge artificial islands project. The project region is divided into a 1000x1000 grid. The whole project will last for N weeks. Each week one unit area of sea will be filled with land.

As a result, new islands (an island consists of all connected land in 4 -- up, down, left and right -- directions) emerges in this region. Suppose the coordinates of the filled units are (0, 0), (1, 1), (1, 0). Then after the first week there is one island:

#...
....
....
....
After the second week there are two islands:

#...
.#..
....
....
After the three week the two previous islands are connected by the newly filled land and thus merge into one bigger island:

#...
##..
....
....
Your task is track the number of islands after each week's land filling.

The first line contains an integer N denoting the number of weeks. (1 ≤ N ≤ 100000)

Each of the following N lines contains two integer x and y denoting the coordinates of the filled area.  (0 ≤ x, y < 1000)

For each week output the number of islands after that week's land filling.

3
0 0
1 1
1 0

1
2

1

【我的程序】

#include <iostream>
using namespace std;

long int n, num=0, a={0}, aSize={0};
int dx={0,0,1,-1};
int dy={1,-1,0,0};

long int findID(long int x)
{
while (a[x]!=x) x=a[x]=a[a[x]];
return x;
}

void unionID(long int x, long int y)
{
x=findID(x); y=findID(y);
if (x==y) return;
if (aSize[x]<aSize[y]) {a[x]=y; aSize[y]+=aSize[x];}
else {a[y]=x; aSize[x]+=aSize[y];}
num--;
}

int check(int x, int y)
{
if (x>=0 && x<1000 && y>=0 && y<1000 && aSize[x*1000+y]>0) return 1; else return 0;
}

int main()
{
long int i,p,q;
cin>>n;

for (i=0;i<n;i++)
{
cin>>p >>q;
a[p*1000+q]=p*1000+q;
aSize[p*1000+q]=1;
num++;

for (int j=0;j<4;j++)
if (check(p+dx[j],q+dy[j])) unionID(p*1000+q,(p+dx[j])*1000+q+dy[j]);

cout<<num <<endl;
}

return 0;
}

01-03 276                                                                          08-01 637
04-24 1090
05-23 1879
05-08 64
10-21 1939
10-12 178
07-30 221
08-23 2707
07-23 3296
05-15 3155
03-13 201
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客