并查集--网络交友

在网络社交的过程中,通过朋友,也能认识新的朋友。在某个朋友关系图中,假定 A 和 B 是朋友,B 和 C 是朋友,那么 A 和 C 也会成为朋友。即,我们规定朋友的朋友也是朋友。

现在要求你每当有一对新的朋友认识的时候,你需要计算两人的朋友圈合并以后的大小。

先输入数字n
再输入n对人名

就比并查集多了一个大小,这个大小用另一个并查集保存一下就行,合并的时候注意将两个集合合并,合并的时候不用两个都增加值,只增加一个,也就是根节点的就行。

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
#include <cctype>
#include <map>

int father[10001];
int sizee[10001];
int get(int x){
    if (father[x] == x) {
        return x;
    }
    return father[x] = get(father[x]);
}

void mergee(int x, int y){
    x = get(x);
    y = get(y);
    if (x != y) {
        father[y] = x;
        sizee[x] += sizee[y];
    }
}

using namespace std;

int main(){
    ios::sync_with_stdio(false);
    map<string, int> m;
    int n, id = 1;
    cin >> n;
    string x, y;
    for (int i = 0; i < n; i++) {
        cin >> x >> y;
        if (!m.count(x)) {
            m[x] = id;
            sizee[m[x]] = 1;
            father[m[x]] = id;
            id++;
        }
        if (!m.count(y)) {
            m[y] = id;
            sizee[m[y]] = 1;
            father[m[y]] = id;
            id++;
        }
        mergee(m[x], m[y]);
        cout << sizee[get(m[x])] << endl;
    }

    return 0;
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值