递归搜索之朋友配对数

来源:互联网 发布:java字符串截取前几位 编辑:程序博客网 时间:2024/06/06 09:35
/*  *这是一道关于暴力搜索的题目,题目要求输入一组朋友关系,然后输出有多少种  *两两朋友组队在一起的方法  *设计:我们使用递归函数来解决,在这个问题中,将整个问题分为n/2个操作,每个  *操作等同于对两名学生的组队,此问题变为:给定还没有组队的学生名单时,计算出  *两名朋友之间组成一对的组合个数,对名单中两名为朋友关系的学生组队后,还是和  *原来一样需要处理同样的问题,所以用递归函数来求解  *Time:2016/4/10*/#include<iostream>#define MAX_F 100using namespace std;int m,n,res=0;//the num of childrenbool areFreiends[MAX_F][MAX_F];//whether two children are friendbool 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;}}//checkif (firstchild == -1) return 1;//all finded.this is one way to do this jobint ret = 0;//else,choose a child with this childfor (int i = firstchild + 1; i < n; i++){if (!leftchildren[i] && areFreiends[firstchild][i]){leftchildren[i] = leftchildren[firstchild] = true; //findedret += 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 relationsfor (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
原创粉丝点击