https://www.icourse163.org/learn/PKU-1002534001?tid=1003136008#/learn/quiz?id=1003986014

对于以下等价类,采用“加权合并规则”(也称“重量权衡合并规则”),进行并查运算,给出最后父节点索引序列。For the following equivalence class, please use “weighted union rule” and UNION/FIND algorithm to write down the final parent node index sequence. 4-0 6-2 8-4 9-4 3-5 9-5 5-2 1-2 7-1 注意:当合并大小相同的两棵树的时候,将第二棵树的根指向第一棵树的根;根节点的索引是它本身;数字之间用空格隔开。 Notice: When we join two trees with the same size, we let the root of the second tree point to the root of the first tree. The index of the root node is itself. Separate the numbers with only one spaces.

using namespace std;
int p[15], Size[15];
void init(){
    for (int i = 0; i < 10; i++) p[i] = i, Size[i] = 1;
}
int Find(int x){
    return x == p[x] ? x :  Find(p[x]);
}
void Union(int a, int b){
    int pa = Find(a), pb = Find(b);
    if (pa != pb){
        if (Size[pa] >= Size[pb]){
            p[pb] = pa;
            Size[pa] += Size[pb];
        }
        else{
            p[pa] = pb;
            Size[pb] += Size[pa];
        }
    }
}

int main(){
	#ifdef ONLINE_JUDGE
	#else
	freopen("in.txt", "r", stdin);
	#endif 
    init();
    for (int i = 0; i < 9; i++){
        int a, b;
        scanf("%d%d", &a, &b);
        Union(a, b);
    }
    for (int i = 0; i < 10; i++){
        printf("%d ", p[i]);
    }
    return 0;
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值