并查集(不带权 + 带权)

来源:互联网 发布:美团数据分析 编辑:程序博客网 时间:2024/06/06 09:58

1. 不带权重并查集

三个操作: 初始化, 查找, 合并.
#include <iostream>#include <cstdio>#include <cmath>using namespace std;const int MAX_SIZE=1002;int Set_father[MAX_SIZE];int Set_Count[MAX_SIZE];void Initialization(){    num=0;    for(int i = 0; i < MAX_SIZE; ++i){        Set_father[i]=i;        Set_Count[i]=0;    }}int find(int p){    if(p==Set_father[p]){        return Set_father[p];    }    return Set_father[p]=find(Set_father[p]);}void Union(int a,int b){    int x,y;    x=find(a);    y=find(b);    if(x!=y){        Set_father[y]=x;    }}

2. 带权重并查集

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int SIZE = 650;const int maxn = 2100;struct node{    int father;    int relation; //表示和父类的关系 一般分为三种, 分别用0, 1, 2 表示. 这样就可以用对3的模来计算并查集中的关系}pic[SIZE];int mark[SIZE];void init(){    for(int i = 0; i < SIZE; ++i){        pic[i].father = i;        pic[i].relation = 0;    } } int find(int p){    if(p == pic[p].father){        return p;    }else{        int x = pic[p].father;        pic[p].father = find(pic[p].father);        pic[p].relation = (pic[p].relation + pic[x].relation) % 3; //对于关系的更新操作        return pic[p].father;    }}void Union(int a, int b, int val) // val表示关系{    int x = find(a);    int y = find(b);    if(x == y){        int r = (pic[b].relation - pic[a].relation + 3) % 3; //对于关系的合并    }else{        pic[y].father = x;        pic[y].relation = (pic[a].relation - pic[b].relation + c +3)%3; // 合并关系        }}
原创粉丝点击