并查集例题POJ1988

http://poj.org/problem?id=1998
一开始用的双向的树结构emmmmmm去提交了一下超时了= =因为我没有压缩路径嘛

#include 
#define N 30004
using namespace std;
int main()
{
    int father[N];
    int son[N];
    for(int i=1;i>p;
    int flag=0;
    for(int j=1;j<=p;++j)
    {
        char oper;
        int fir,sec;
        cin>>oper;
        if(oper=='M'){
            cin>>fir>>sec;
            int a=fir,b=sec;
            while(son[a]!=a)
            {
                a=son[a];
            }
            while(father[b]!=b)
            {
                b=father[b];
            }
            son[a]=b;
            father[b]=a;
        }
        if(oper=='C'){
            int num=0;
            cin>>fir;
            int a=fir;
            while(son[a]!=a){
                a=son[a];
                ++num;
            }
            if(flag)
                cout<

参考了蓝书
压缩路径的那个find想不明白T_T想了好久
这个root数组名字取的也太有误解性了!!这里存的不是到根节点的距离啊而是到父节点的距离


并查集例题POJ1988_第1张图片
算法解析.jpg
并查集例题POJ1988_第2张图片
对递归的理解.jpg
#include 
#include 
#include 
using namespace std;
#define N 30004

int n,father[N],root[N],number[N];
//root表示到根结点的距离,number表示这个集合中有多少盒子
void init()
{
    int i;
    for(i=1;i>p;
    int flag=0;
    for(int k=1;k<=p;++k)
    {
        char oper;
        cin>>oper;
        if(oper=='C'){
            cin>>i;
            int f=find(i);
            if(flag)
                cout<>i>>j;
            U(i,j);
        }
    }
    return 0;
}

你可能感兴趣的:(并查集例题POJ1988)