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 <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; }