http://acm.nbut.cn/Contest/view/id/43/problem/B.xhtml
- 问题描述
-
Death-Moon loves telling stories.
Some days ago, he told us a funny story.Long long ago, there is a hamster who is so naughty. Now, he comes to a place likes a N * N square. so, he is so excited to drill holes underground.
- 输入
-
Input until EOF.
Fisrt input two integers N (3 <= N < 100) and M (0 < M <2000). N is the side of N * N ground, M is the number of operations.
Then follow M lines.
Each line is a command:
Out x y : Hamster will get out at (x, y) from underground. So, place (x, y) will be a hole.
P : Calculate out the number of the holes and output (Two holes are connected when they share an edge).
If two holes are connected, it means it is one hole. - 输出
-
For each 'P' command, output the number of the holes. Maybe hamster will get out at the same place more than once
思路,用hash和并查积
代码:
-
View Code
#include <cstdio> #include <set> #include <cstring> using namespace std; #define N 101 int f[N * N * N]; int a[N][N]; set<int> v; int ff(int x) { if(f[x] == x) return x; return ff(f[x]); } int main() { int n,m; while(~scanf("%d %d",&n,&m)) { memset(a,0,sizeof(a)); char s[10]; v.clear(); for(int i = 1;i <= n;i ++) for(int j = 1;j <= n;j ++) f[i * 10000 + j] = i * 10000 + j; while(m --) { scanf("%s",s); if(s[0] == 'P') printf("%d\n",v.size()); else { int x,y,p,q; scanf("%d %d",&x,&y); x ++; y ++; q = ff(x * 10000 + y); a[x][y] = 1; set<int>:: iterator cp; if(!a[x - 1][y] && !a[x + 1][y] && !a[x][y - 1] && !a[x][y + 1]) { v.insert(x * 10000 + y); } if(a[x - 1][y]) { int u = (x - 1) * 10000 + y; p = ff(u); f[p] = q; cp = v.find(p); if(cp != v.end()) v.erase(cp); v.insert(q); } if(a[x + 1][y]) { int u = (x + 1) * 10000 + y; p = ff(u); f[p] = q; cp = v.find(p); if(cp != v.end()) v.erase(cp); v.insert(q); } if(a[x][y - 1]) { int u = x * 10000 + y - 1; p = ff(u); f[p] = q; cp = v.find(p); if(cp != v.end()) v.erase(cp); v.insert(q); } if(a[x][y + 1]) { int u = x * 10000 + y + 1; p = ff(u); f[p] = q; cp = v.find(p); if(cp != v.end()) v.erase(cp); v.insert(q); } } } } return 0; }