并查集与并查集模板

  并查集  我也就是会一点粗浅应用,要是真叫我讲我也不会形容,你们还是去网上看百度百科吧。

  然后就是一些例题与模板。

p1699 

  

  这应该是巨裸的并查集的题了,没有一点点的拐弯抹角。不给代码。

 p1698 银河英雄传

  这道就有点难了。它需要记录一个before[i]表示i之前的战舰数量......

  丢出代码

int M=30010;
int T,t1,t2,f1,f2;
int father[M],before[M],after[M];
char temp;
int getfather(int xx)
{
    int yy=father[xx];
    if(yy!=xx)
    {
        father[xx]=getfather(yy);
        before[xx]+=before[yy];
    }
    return father[xx];
}
void merge(int xx,int yy)//xx.head to yy.tail
{
    f1=getfather(xx),f2=getfather(yy);
    father[f1]=f2;
    before[f1]=after[f2];
    after[f2]+=after[f1];
}
int main()
{ios::sync_with_stdio(false);
//freopen("123.in","r",stdin);
//freopen("123.out","w",stdout);
    for(int i=1;i<M;i++)
        father[i]=i,before[i]=0,after[i]=1;
    cin>>T;
    for(int i=1;i<=T;i++)
    {
        cin>>temp>>t1>>t2;
        if(temp=='M')
            merge(t1,t2);
        else
        {
            f1=getfather(t1),f2=getfather(t2);
            if(f1!=f2)
                cout<<-1<<endl;
            else
                cout<<abs(before[t1]-before[t2])-1;
        }
    }
    return 0;
}

最后分享一下从书中翻到的模板好了:

int fa[?];
int get(int x)
{
    if(x==fa[x])return x;        
    return fa[x]=get(fa[x]);//路径压缩
}
void hebing(int x,int y)
{
    fa[get(x)]=get(y);
}


 

猜你喜欢

转载自www.cnblogs.com/qywyt/p/8970875.html