/*
*这是一道关于暴力搜索的题目,题目要求输入一组朋友关系,然后输出有多少种
*两两朋友组队在一起的方法
*设计:我们使用递归函数来解决,在这个问题中,将整个问题分为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);
}
递归搜索之朋友配对数
最新推荐文章于 2021-02-10 13:42:50 发布