capacity 1988

Beginning with n pieces of wood in a row, there are two modes of operation, the first one is to m where that pile to pile on top of n is located, is the second piece of wood m below the query how many pieces of wood.
Disjoint-set with the lowermost recording block is the root block to a block to which the distance is the distance from the bottom of the root.
If there is a component of the communication block 2, there are three block b, then a distance from the root to the root of b is 3, and this can be seen from the size of the connected components is associated, so use an array of records.
When the query is likely the root of the current is not updated, so the first update path

And check-depth understanding of the set: essentially disjoint-set forest, take disjoint-set to think more in the direction of the tree.

#include <cstdio>
#include <cstring>
using namespace std;
const int N = 30000 + 10 ;
int fa[N],son[N],n,x,y,dis[N];
int find(int x){
	if(x == fa[x]) {
		return x;
	}
	int tmp = fa[x];
	fa[x] = find(fa[x]);
	dis[x] += dis[tmp];
	return fa[x];
}
void Union(int x,int y){
	x = find(x); y = find(y);
	if(x != y){
		fa[x] = y;
		dis[x] = son[y];
		son[y] += son[x];
	}
}
char s[2];
int main(){
	while(~scanf("%d",&n)) {
		for(int i = 1;i<N;i++) fa[i] = i,son[i] = 1;
		memset(dis,0,sizeof(dis));
		for(int i = 0;i<n;i++){
			scanf("%s",s);
			if(s[0] == 'M') {
				scanf("%d%d",&x,&y);
				Union(x,y);
			}
			else {
				scanf("%d",&x);
				find(x) ;
				printf("%d\n",dis[x]);
			}
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/winhcc/article/details/89553765