hihocoder Counting Islands II(并查集)

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 <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <ext/rope>
#define rep(i,m,n) for(i=m;i<=n;i++)
#define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++)
#define vi vector<int>
#define pii pair<int,int>
#define mod 1000000007
#define inf 0x3f3f3f3f
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define pi acos(-1.0)
const int maxn=1e5+10;
using namespace std;
using namespace __gnu_cxx;
const int N = 1100005;
int pre[N],ans[1005][1005];
int d[4][2]= {0,1,1,0,0,-1,-1,0};
int n,cnt=0;
set<int>sa;
int Find(int x)
{
    if(pre[x] != x)
        pre[x] = Find(pre[x]);
    return pre[x];
}
void init()
{
    for(int i=0; i<N; i++)pre[i]=i;
}
int main()
{
    init();
    int X,Y;
    int g=0;
    cin>>n;
    for(int i=0; i<n; i++)
    {
        g++;
        cin>>X>>Y;
        ans[X][Y]=1;
        for(int j=0; j<4; j++)
        {
            int xx=X+d[j][0];
            int yy=Y+d[j][1];
            if(xx>=0&&xx<1000&&yy>=0&&yy<1000)
            {
                if(ans[xx][yy]==1)
                {
                    int aa=Find(xx*1000+yy),bb=Find(X*1000+Y);
                    if(aa!=bb)pre[aa]=bb,g--;
                }
            }
        }
        cout<<g<<endl;
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/jianrenfang/p/5711759.html