递归搜索之朋友配对数

/*
  *这是一道关于暴力搜索的题目,题目要求输入一组朋友关系,然后输出有多少种
  *两两朋友组队在一起的方法
  *设计:我们使用递归函数来解决,在这个问题中,将整个问题分为n/2个操作,每个
  *操作等同于对两名学生的组队,此问题变为:给定还没有组队的学生名单时,计算出
  *两名朋友之间组成一对的组合个数,对名单中两名为朋友关系的学生组队后,还是和
  *原来一样需要处理同样的问题,所以用递归函数来求解
  *Time:2016/4/10
*/

#include<iostream>

#define MAX_F 100
using namespace std;

int m,n,res=0;//the num of children
bool areFreiends[MAX_F][MAX_F];//whether two children are friend
bool leftC[MAX_F];

int countpair(bool leftchildren[MAX_F])
{
	//find the left children<not pair.>
	int firstchild = -1;
	for (int i = 0; i < n; ++i){
		if (!leftchildren[i]){
			firstchild = i;
			break;
		}
	}
	//check
	if (firstchild == -1) return 1;//all finded.this is one way to do this job
	int ret = 0;
	//else,choose a child with this child
	for (int i = firstchild + 1; i < n; i++){
		if (!leftchildren[i] && areFreiends[firstchild][i]){
			leftchildren[i] = leftchildren[firstchild] = true; //finded
			ret += countpair(leftchildren);
			leftchildren[i] = leftchildren[firstchild] = false;//for next test
		}
	}
	return ret;
}

int main()
{
	struct { int l, r; }p;
	for (;;){
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				areFreiends[i][j] = false;
		cin >> n>>m;//the num of children and relations
		for (int i = 0; i < m; i++){
			cin >> p.l >> p.r;
			areFreiends[p.l][p.r] = true;
			areFreiends[p.r][p.l] = true;
		}
		memset(leftC, false,MAX_F);
		cout << "The result is:" << countpair(leftC) << endl;
	}
   exit(EXIT_SUCCESS);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值