TOJ 2784 带权并查集+Map

本文介绍了一种使用带权并查集算法解决社交网络中好友关系动态更新的问题,通过实例演示了如何跟踪并计算每对新好友关系形成时的社交网络总人数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2784: Virtual Friends 分享至QQ空间
时间限制(普通/Java):1000MS/3000MS 内存限制:65536KByte
总提交: 254 测试通过:56
描述

These days, you can do all sorts of things online. For example, you can use various websites to make virtual friends. For some people, growing their social network (their friends, their friends’ friends, their friends’ friends’ friends, and so on), has become an addictive hobby. Just as some people collect stamps, other people collect virtual friends.

Your task is to observe the interactions on such a website and keep track of the size of each person’s network.

Assume that every friendship is mutual. If Fred is Barney’s friend, then Barney is also Fred’s friend.

输入

The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer F, the number of friendships formed, which is no more than 100 000. Each of the following F lines contains the names of two people who have just become friends, separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase).

输出

Whenever a friendship is formed, print a line containing one integer, the number of people in the social network of the two people who have just become friends.

样例输入

1
3
Fred Barney
Barney Betty
Betty Wilma

样例输出

2
3
4

题目来源

Waterloo Sep.27 2008
题解:带权并查集加 map 的映射,题意是求每次有新人时的总人数

#include<bits/stdc++.h>
using namespace std;
int pre[100010],num[100010]; //父节点数组和数量数组
int Find(int x){ //找根节点
    int son=x,tmp;
    while(pre[x]!=x) //不是根节点,继续往上搜索
        x=pre[x];
    while(son!=x){ //路径压缩,把所有的子节点都链接到根节点上去
        tmp=pre[son];
        pre[son]=x;
        son=tmp;
    }
    return x;
}
void Jion(int x,int y){
    int r1=Find(x);
    int r2=Find(y);
    if(r1!=r2)
    pre[r2]=r1,num[r1]+=num[r2]; //新朋友就加入
    cout<<num[r1]<<endl; //输出当前的人数
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        map<string,int>mymap;
        int n,cnt=0;
        scanf("%d",&n);
        for(int i=1;i<100001;i++)
            pre[i]=i,num[i]=1; //开始所有人都指向自己,人数都为1
        while(n--){
            string a,b;
            cin >> a >> b;
            if(!mymap[a]) mymap[a]=++cnt; //有无出现过这个人
            if(!mymap[b]) mymap[b]=++cnt; //没有的话就给一个数字标记
            Jion(mymap[a],mymap[b]);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值