并查集
/*并查集*/ #include<stdio.h> int *a; int *sz; int count; //the number of connected component //union two connected components with weights void union_two_points(int p, int q) { int i = root(p); int j = root(q); if(i == j) return; if(sz[i] < sz[j]) { a[i] = j; sz[j] += sz[i]; } else { a[j] = i; sz[i] += sz[j]; } count--; } //test if p and q are connected int connected(int p, int q) { return root[p] == root[q]; } //find the root point int root(int p) { while(p != a[p]) { p = a[p]; } return p; } int main() { int T; printf("Please input the number of points:"); scanf("%d",&T); count = T; a = (int*)malloc(sizeof(int)*T); sz = (int*)malloc(sizeof(int)*T); memset(sz,1,T*sizeof(int)); //set the size array //initial the array for(int i=0;i<T;i++) { a[i] = i; } /* operation */ }