HDU-3172-Virtual Friends

ACM模版

描述

描述

题解

带权并查集,这里需要用到字典树来搞一个映射,把名字映射成ID即可。

注意啦,注意啦,这里有一个坑,绝对坑死人,有多组数据,这里说的是T外还要套一层while,真是个暗坑!!!

代码

#include <iostream>
#include <string>
#include <map>

using namespace std;

const int MAXN = 2e5 + 10;

int pre[MAXN];
int sum[MAXN];
int total;

map<string, int> people; //  用map来处理人名与数字下标之间的对应关系

int find(int x)
{
    if (x != pre[x])
    {
        pre[x] = find(pre[x]);
    }
    return pre[x];
}

int join(int x, int y)
{
    int fx = find(x);
    int fy = find(y);

    if (fx != fy)
    {
        pre[fx] = fy;
        sum[fy] += sum[fx];
    }

    return sum[fy];
}

int main()
{
    int T, n;
    string a, b;

    while (cin >> T)
    {
        while (T--)
        {
            total = 0;
            people.clear();

            scanf("%d", &n);
            while (n--)
            {
                cin >> a >> b;
                if (people.find(a) == people.end())
                {
                    total++;
                    people[a] = total;
                    pre[total] = total;
                    sum[total] = 1;
                }
                if (people.find(b) == people.end())
                {
                    total++;
                    people[b] = total;
                    pre[total] = total;
                    sum[total] = 1;
                }
                int ans = join(people[a], people[b]);
                printf("%d\n", ans);
            }
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值