算法:并查集的实现及简单优化

来源:互联网 发布:windows查看显存 编辑:程序博客网 时间:2024/06/08 12:22

参考的《挑战程序设计竞赛》一书中的并查集的实现。
(另外,阿克曼(Ackermann)函数是什么鬼???)

int parent[MAX_N];int height[MAX_N];void init(int n){    for(int i=0;i<n;i++){        parent[i]=i;        height[i]=0;    }}int find(int x){    if(parent[x]==x){        return x;    }    else{        return parent[x]=find(parent[x]);    }}//非递归的并查集查找 //int find(int x){//  int root=x,tmp;//  while(parent[root]!=root){//      root=parent[root];//  }//  while(parent[x]!=root){//      tmp=parent[x];//      parent[x]=root;//      x=tmp;//  }//  return root;//}void unite(int x,int y){    x=find(x);    y=find(y);    if(x==y) return;    if(height[x]<height[y]){        parent[x]=y;    }    else{        parent[y]=x;        if(height[x]==height[y]){            height[x]++;        }    }}bool same(int x,int y){    return find(x)==find(y);}