Counting Islands II

计数岛屿:并查集实现
本文介绍了一个使用并查集算法解决岛屿计数问题的方法。在一个1000x1000的网格中,每周填充一个海域单元为陆地,形成岛屿。文章详细解释了如何通过并查集跟踪每星期形成的岛屿数量,并提供了完整的C++代码实现。

Counting Islands II

描述

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>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
#include <string>
#include <cstring>
#define rep(i,m,n) for(i=m;i<=n;i++)
#define pii pair<int,int>
#define fi first
#define se second
#define mp make_pair
#define pb push_back
const int maxn=1e6+10;
using namespace std;
int n,m,p[maxn],ans;
char mip[1010][1010];
int fa(int x)
{
    return p[x]==x?x:p[x]=fa(p[x]);
}
void work(int x,int y)
{
    ans++;
    int a,b;
    if(x-1>=0&&mip[x-1][y]=='#')
    {
        a=fa(x*1000+y),b=fa((x-1)*1000+y);
        if(a!=b)p[a]=b,ans--;
    }
    if(x+1<1000&&mip[x+1][y]=='#')
    {
        a=fa(x*1000+y),b=fa((x+1)*1000+y);
        if(a!=b)p[a]=b,ans--;
    }
    if(y-1>=0&&mip[x][y-1]=='#')
    {
        a=fa(x*1000+y),b=fa(x*1000+y-1);
        if(a!=b)p[a]=b,ans--;
    }
    if(y+1<1000&&mip[x][y+1]=='#')
    {
        a=fa(x*1000+y),b=fa(x*1000+y+1);
        if(a!=b)p[a]=b,ans--;
    }
    return;
}
int main()
{
    int i,j,k,t;
    rep(i,0,maxn-10)p[i]=i;
    memset(mip,'.',sizeof(mip));
    scanf("%d",&n);
    while(n--)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        mip[x][y]='#';
        work(x,y);
        printf("%d\n",ans);
    }
    //system("pause");
    return 0;
}

 

转载于:https://www.cnblogs.com/dyzll/p/5711474.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值