当前位置: 代码迷 >> 综合 >> 2021秋季《数据结构》_EOJ 1082. Virtual Friends
  详细解决方案

2021秋季《数据结构》_EOJ 1082. Virtual Friends

热度:15   发布时间:2023-12-10 19:43:42.0

题目

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.在这里插入图片描述

思路

并查集应用,开map
需要注意的是,结构体不能作为map的key,而std::map是一个有序关联容器,它会在内部给key值排序,由此报错。于是新开一个getCnt记录count。

代码

#include<bits/stdc++.h>
using namespace std;
#define MAXN 100001struct node
{
    string name = "0";
};string findSet(map<string, node>& parent, string s)
{
    string tmp = s;while (parent[tmp].name != "0"){
    tmp = parent[tmp].name;}while (s != tmp){
    string t = parent[s].name;parent[s].name = tmp;s = t;}return tmp;
}string unionSet(map<string, node>& parent, map<string, int>& getCnt,node first, node next)
{
    string s1 = first.name;string s2 = next.name;string root1 = findSet(parent, s1);string root2 = findSet(parent, s2);//cout << "s1=" << s1 << ' ' << "s2=" << s2 << ' ' << "root1=" << root1 << ' ' << "root2=" << root2 << endl;if (root1 == root2)return root1;int tmpCnt = getCnt[root1] + getCnt[root2];// cout << "tmpCnt=" << tmpCnt << endl;if (getCnt[root1] >= getCnt[root2]){
    parent[root2].name = root1;getCnt[root1] = tmpCnt;//cout << "root1=" << root1 << ' ' << getCnt[root1] << endl;return root1;}else{
    parent[root1].name = root2;getCnt[root2] = tmpCnt;return root2;}
}int main()
{
    int t; cin >> t;for (int q = 0; q < t; q++){
    map<string, node> parent;map<string, int> getCnt;int f; cin >> f;for (int i = 0; i < f; i++){
    node first, next;cin >> first.name >> next.name;if (parent.count(first.name) == 0)getCnt[first.name] = 1;if (parent.count(next.name) == 0)getCnt[next.name] = 1;string tmpRes = unionSet(parent, getCnt, first, next);//cout << '*' << tmpRes << endl;cout << getCnt[tmpRes] << endl;}}return 0;
}
  相关解决方案