练习题:网络交友(并查集基础)


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

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

第一行:一个整数 n(n\leq 5000)n(n≤5000),表示有 nn 对朋友认识。

接下来 nn 行:每行输入两个名字。表示新认识的两人的名字,用空格隔开。
(名字是一个首字母大写后面全是小写字母且长度不超过 20 的串)。

输出格式

对于每一对新认识的朋友,输出合并以后的朋友圈的大小。

样例输入

3 
Fred Barney 
Barney Betty 
Betty Wilma 
样例输出

2 
3 
4

 自己的AC代码:直接用string来连接

#include<iostream>
#include<string>
#include<map>
using namespace std;
map<string,string> father;
map<string,int> sizes;

string get(string x)
{
	if( father[x] == x )
	{
		return x;
	}
//	cout<<x<<" 的小弟数量 "<<dis[x]<<endl; 
	return get( father[x] );
	//查找根节点 
}
void merge (string x,string y)//a接在b后面 
{
	string a , b;
	a = get(x);
	b = get(y);
	if( a != b )
	{
		father[a] = b; 
		sizes[b] += sizes[a];
	}
 	cout<<sizes[b]<<endl; 
	
}
int main()
{
	ios::sync_with_stdio(false);
	int n,i,id=1;
	string a,b;
	cin>>n;
	
	for(i=0;i<n;++i)
	{
		cin>>a>>b;
		if(father[a]=="")
		{
			father[a] = a;
	    	        sizes[a] = 1;
		} 
		if(father[b]=="")
		{
			father[b] = b;
			sizes[b] = 1;	
		} 
		merge(a,b);		
	 } 
	return 0;
}

 大佬的AC代码:利用 map.count() 来把字符串之间的关系转化为整形的

#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;
}  
--------------------- 
作者:ACkook 
来源:CSDN 
原文:https://blog.csdn.net/zxk_hi/article/details/79021949 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_42580577/article/details/87834956