poj 2542

 题意:给定多组(x,y),x和y的信仰相同,估计信仰的数量

 解法:并查集,初始化ans为总人数,当添加一对(x,y)后,判断,如果已经是一组了,不做,如果不是,ans-1.



#include 
#include 
#include 

/*
  *This file is about union set operations.
  *and the program is c-style,you can transfer it to 
  *cpp-style.
  *you can copy,re-write,sell this program but no need to
  *let me know this.but you need copy this comment to your
  *program's header comment.
  *hujian nankai university
  *2016/5/26
*/

#define UNION_SET_MAX_SIZE 1024*50 //the size of union.

//the parent array
int parent[UNION_SET_MAX_SIZE];

//the height of the union tree
int rank[UNION_SET_MAX_SIZE];

//the size of union
int union_size=0;

//the ans
int ans=0,n,m;


//initialze the union set
void init_set(int s)
{
    int i;
    for(i=0;i<=s;i++){
        parent[i]=i;
        rank[i]=0;
    }
}

//find the root of this tree
int find_set(int x){
    if(x==parent[x]){
        return x;
    }else{
       return parent[x]=find_set(parent[x]);
    }
}

//union x and y is the root of each tree
void union_set(int x,int y)
{
    x=find_set(x);
    y=find_set(y);
    if(x==y)  return;//same tree
    
    //x and y have same religions
    ans--;
    
    if(rank[x]

你可能感兴趣的:(poj,c/c++,数据结构,Data,structure,SET,算法与数据结构题目解析,C++,算法,poj,并查集)