Almost Union-Find(Uva 11987)并查集

来源:互联网 发布:我国人口增长数据 编辑:程序博客网 时间:2024/06/05 20:37

来自《算法竞赛入门经典训练指南》

1.题目原文

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3138

2.解题思路

题目给出的三种操作,符合并查集的模式。不同的是操作2。
2 p q:把酸雨p移动到q所在集合。如果二者已经在一个集合中,忽略此操作。
这时p的集合就会发生变化,如果p是所属集合的根节点,就需要调整这个集合。为了这种删除根节点的情况出现,我们把1-n所有节点的根节点指向1+n-2n。即初始化,点i的父亲节点是i+n。这样就和一般的并查集一样了。

3.AC代码

#include <algorithm>#include <cctype>#include <cmath>#include <cstdio>#include <cstdlib>#include <cstring>#include <iomanip>#include <iostream>#include <map>#include <queue>#include <string>#include <set>#include <vector>#include<cmath>#include<bitset>#include<sstream>using namespace std;#define INF 0x7fffffff#define maxn 200005int n,m;int father[maxn];int sum[maxn],num[maxn];void init(){    for(int i=1;i<=n;i++){        father[i]=i+n;        father[i+n]=i+n;        sum[i+n]=i;        num[i+n]=1;    }}int Find(int x){    if(x!=father[x]){        father[x]=Find(father[x]);    }    return father[x];}int main(){    while(scanf("%d%d",&n,&m)!=EOF){        init();        int mark,p,q;        for(int i=0;i<m;i++){            scanf("%d",&mark);            if(mark==1){                scanf("%d%d",&p,&q);                int fatherP=Find(p);                int fatherQ=Find(q);                if(fatherP!=fatherQ){                    father[fatherP]=fatherQ;                    sum[fatherQ]+=sum[fatherP];                    num[fatherQ]+=num[fatherP];                }            }            else if(mark==2){                scanf("%d%d",&p,&q);                int fatherP=Find(p);                int fatherQ=Find(q);                if(fatherP!=fatherQ){                    father[p]=fatherQ;                    sum[fatherQ]+=p;                    sum[fatherP]-=p;                    num[fatherP]--;                    num[fatherQ]++;                }            }            else{                scanf("%d",&p);                int fatherP=Find(p);                printf("%d %d\n",num[fatherP],sum[fatherP]);            }        }    }    return 0;}


0 0
原创粉丝点击