并查集
Posted dzy521
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了并查集相关的知识,希望对你有一定的参考价值。
/*并查集*/ #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 */ }
以上是关于并查集的主要内容,如果未能解决你的问题,请参考以下文章