文章标题 HDU 3172 : Virtual Friends (并查集+map)

本文介绍了一个使用并查集算法来追踪虚拟社交网络中个人社交圈规模的问题。通过映射姓名到整数,实现对每一对成为朋友的关系进行处理,并即时更新和输出他们的社交网络规模。

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

Virtual Friends

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.
Input
Input file contains multiple test cases.
The first line of each case indicates the number of test friendship nest.
each friendship nest begins with a line containing an integer F, the number of friendships formed in this frindship nest, 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).
Output
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.
Sample Input
1
3
Fred Barney
Barney Betty
Betty Wilma
Sample Output
2
3
4
题意:有一种虚拟的朋友,比如你的朋友,你的朋友的朋友,朋友的朋友的朋友都是你的虚拟朋友,每次输入两个名字表示这两个人是虚拟朋友,然后每次输入要输出这两个人的虚拟朋友的数目。
分析:用并查集,每次将两个人名映射成一个整数,然后通过并查集求出这两个人的虚拟朋友 的数目。映射的话可以用map映射成一个数字。
代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue> 
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
int F;
int fa[100005*2];//乘以2因为每次有两个人名 
int num[100005*2];
int find(int x){
    return x==fa[x]?x:fa[x]=find(fa[x]);
}
void merge(int u,int v){
    int fu=find (u);
    int fv=find (v);
    if (fu==fv)return ;
    fa[fu]=fv;
    num[fv]+=num[fu];
}
map<string,int>mp; 
int main ()
{
    int t;

    string a,b;
    int cnt;
    while (cin>>t){//多组输入 
        while (t--){
            cnt=1;
            mp.clear();
            for (int i=0;i<=200000;i++){//初始化 
                fa[i]=i;
                num[i]=1;
            }
            cin>>F;
            while (F--){
                cin>>a>>b;
                if (mp.find(a)==mp.end()){//判断人名a出现过没有,没有就给其附一个编号 
                    mp[a]=cnt++;
                } 
                if (mp.find(b)==mp.end()){//同上 
                    mp[b]=cnt++;
                }
                merge(mp[a],mp[b]);//合并 
                cout<<num[find(mp[a])]<<endl;//求出数目 
            }
        }
    }       
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值