有编号分别为0,1,2,3,4的5本书,准备分给5个人A,B,C,D,E,每个人阅读兴趣用一个二维数组加以描述,公式如下:
1 i喜欢j书
Like[i][j] =
0 i不喜欢j书
写一个程序,输出所有分书方案,让人人皆大欢喜。假定5个人对5本书的阅读兴趣如下图所示。
答案
a 2
b 0
c 1
d 3
e 4
要程序先采纳
这里的知识点是图的遍历为题 很简单,自己做出来才有成就感的,建议你看下图的深度优先遍历,广度优先遍历 这里是深度优先遍历的链接(深度优先比较容易理解)
bool Interest[5][5]={{0,0,1,1,0},{1,1,0,0,1},{0,1,1,0,1},{0,0,0,1,0},{0,1,0,0,1}};//兴趣
bool book[5]={1,1,1,1,1};//书籍是否被选择
bool Distribution(char name)
{
for(int i=0;i<5;i++)
{
if(Interest[name-'A'][i]==true && book[i]==true)
{
book[i]=false;
if(Distribution(++name)==true || name=='E'+1)
{
book[i]=true;
printf("%c choose %d ,",--name,i);
return true;
}
else
{
book[i]=true;
return false;
}
}
}
return false;
}
int main()
{
Distribution('A');
return 0;
}
最后输出是E choose 4,D choose 3 ,C choose 1, B choose 0 ,A choose 2,
大半夜的,干嘛递归呢
5个for循环妥妥的
int num=0;
struct answer
{
int a,b,c,d,e;
}ANSWER;
ANSWER[] answer;
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
for(intk=0;k<5;k++)
for(int l=0;l<5;l++)
for(int m=0;m<5;m++)
{
if(Like[0][i]==1&&Like[1][j]==1&&Like[2][k]==1&&Like[3][l]==1&&Like[4][m]==1)
{
answer[num].a=i;
answer[num].b=j;
answer[num].c=k;
answer[num].d=l;
answer[num].e=m;
}
大半夜的,干嘛递归呢
5个for循环妥妥的
int num=0;
struct answer
{
int a,b,c,d,e;
}ANSWER;
ANSWER[] answer;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
if(i==j) continue;
for(intk=0;k<5;k++)
{
if(i==k||j==k) conintue;
for(int l=0;l<5;l++)
{
if(i==l||j==l||k==l) continue;
for(int m=0;m<5;m++)
{
if(i==m||j==m||k==m||l==m) continue;
else
{if(Like[0][i]==1&&Like[1][j]==1&&Like[2][k]==1&&Like[3][l]==1&&Like[4][m]==1)
{
answer[num].a=i;
answer[num].b=j;
answer[num].c=k;
answer[num].d=l;
answer[num].e=m;
}
}
}
}
}
#include <iostream>
#include <string.h>
using namespace std;
int like[5][5] =
{
{0,0,1,1,0},
{1,1,0,0,1},
{0,1,1,0,1},
{0,0,0,1,0},
{0,1,0,0,1}
};
void dofind(int * pre, int n)
{
if (n == 5)
{
for (int i=0;i<5;i++)
cout << (char)(i + 65) << " " << pre[i] << endl;
return;
}
int a[5] = { 0, 0, 0, 0, 0 };
for (int i=0;i<n;i++)
{
a[pre[i]]=1;
}
for (int i = 0; i < 5; i++)
{
if (like[n][i] == 1 && a[i] == 0)
{
int * p = new int[n + 1];
memcpy(p, pre, sizeof(int) * n);
p[n] = i;
dofind(p, n + 1);
}
}
}
int main()
{
int emptyarr[] = {};
dofind(emptyarr, 0);
return 0;
}
A 2
B 0
C 1
D 3
E 4
A 2
B 0
C 4
D 3
E 1