# 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 302
08-01 657
04-24 1770
08-04 1183
10-12 231
07-30 322
10-21 2074
05-23 2419
09-06 1185
08-23 5406
05-08 313
07-23 3574
09-14 1577
08-18 2596
03-13 255
04-11 719
03-27 594
04-30 515
06-03 493

### “相关推荐”对你有帮助么？

•  非常没帮助
•  没帮助
•  一般
•  有帮助
•  非常有帮助

©️2022 CSDN 皮肤主题：大白 设计师：CSDN官方博客 被折叠的  条评论 为什么被折叠? 到【灌水乐园】发言 ¥2 ¥4 ¥6 ¥10 ¥20  余额支付 (余额：-- )  扫码支付 获取中  扫码支付 点击重新获取   扫码支付 1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。 余额充值