小米2013招聘笔试题:朋友圈

题目:

假如已知有n个人和m对好友关系(存于数字r)。如果两个人是直接或间接的好友(好友的好友的好友...),则认为他们属于同一个朋友圈,请写程序求出这n个人里一共有多少个朋友圈。
假如:n = 5 , m = 3 , r = {{1 , 2} , {2 , 3} , {4 , 5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友,则1、2、3属于一个朋友圈,4、5属于另一个朋友圈,结果为2个朋友圈。

解析:

这道题本质上可以理解为求图的连通子图的个数,而求连通子图的个数问题则可以用不相交的集合来求解。至于不相交的集合的知识可以参见算法导论的第21章。

下面给出本人的源代码如下(代码尚未调试,故可能会有些bug):

#include <iostream>
using namespace std;

template<class T> struct Node
{
	Node* parent;
	int rank;
	T value;
	
	Node(const T& v)
	:parent(NULL), randk(0), value(v)
	{}
}//struct

/*
*返回指定节点所在的集合
*/
Node* find_root(Node* rhs)
{
	Node* root = NULL;
	if(rhs != NULL)
	{
		Node* t = rhs;
		while(t->parent != NULL) t = t->parent;
	}//if(rhs != NULL)
	root = t;
	
	//将节点rhs到根节点路径上的节点的parent直接指向根节点
	Node* q = rhs, p = rhs->parent;
	while(p != NULL) 
	{
		q->parent = root;
		q = p;
		p = p->parent;
	}//while(q->parent != NULL)
	
	return root;
}//find_root

/*
*合并节点x和节点y所在的集合
*/
void union_set(Node* x, Node* y)
{
	if(x == NULL || y == NULL) return;
	Node* root_x = find_root(x);
	Node* root_y = find_root(y);
	if(root_x == root_y) return;
	
	//合并两个集合
	if(root_x->rank < root_y->rank)
	{
		Node* t = root_x;
		root_x = root_y;
		root_y = t;
	}//if(root_x->rank < root_y->rank)
	root_y->parent = root_x;
	if(root_x->rank == root_y->rank) root_x->rank += 1;
}//union_set

int main()
{
	int n;	//人数
	int m;	//关系对数
	while(cin >> n >> m && n > 0 && m >= 0)
	{
		vector<Node<int> > P;
		P.reserve(n);
		for(int i = 0; i < n; i++)
		{
			P.push_back(Node<int>(i));
		}//for(int i = 0; i < n; i++)
		
		//根据朋友关系计算朋友圈的个数
		int circle_count = n;
		int person1, person2;
		for(int i = 0; i < m; i++)
		{
			cin >> person1 >> person2;
			if(circle_count == 1) continue;	//若当前圈子已经为1,则没有必要继续后续的计算
			if(find_root(P[person1]) != find_root(P[person2]))	//读取当前关系对时,person1和person2不在同一个圈子里
			{
				if(circle_count > 1) circle_count--;	
				union_set(P[person1], P[person2]);
			}//if(find_root(P[person1]) != find_root(P[person2]))
		}//for(int i = 0; i < m; i++)
		
		//输出圈子数
		cout << "当前圈子数为: " << circle_count << endl;
	}//while(cin >> n >> m && n > 0 && m >= 0)
}//main


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值