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;
}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)
{
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;
}
}