c语言李白喝酒答案,李白喝酒问题的算法

自己先粗略的写了一下,刚调试了一下,还是有点问题,已经被他折磨了两个小时了,先休息会儿等会儿再来debug!

结果debug了好久,也没我想的那么简单,也没人提示,今天又花了半个小时左右的时间,终于找到了问题的所在!

#include

using namespace std;

int counting = 0;

int A[15];

int sum = 2;

int collectArray()

{

int collect = 0;

for(int i =0;i<15;++i)

{

if(A[i] == 0)

collect++;

}

return collect;

}

void enumAll(int pos)

{

if(pos == 15)

{

if(sum ==0 && A[14] == 1 )

{

counting++;

}

}else{

if(collectArray() <= 5)

{

A[pos] = 0;

sum *= 2;

enumAll(pos+1);

A[pos] = 1;

sum -= 1;

enumAll(pos+1);

}

/*if( <= 10)

{

A[pos] = 1;

enuAll(pos+1);

A[pos] = 0;

enumAll(pos+1);

}*/

}

}

int main()

{

for(int i =0;i<15;++i)

{

A[i] = -1;

}

enumAll(0);

cout << counting;

return 0;

}

更新版本,已通过测试:

#include

using namespace std;

int counting = 0;

int A[15];

int sum = 2;

int collectArray()

{

int collect = 0;

for(int i =0;i<15;++i)

{

if(A[i] == 0)

collect++;

}

return collect;

}

void enumAll(int pos,int sonSum)

//直接采用枚举方法,A[]中每个元素不是0就是1

//若采用if判断则会产生15层嵌套

//因此采用树的深度优先遍历

//建议我使用栈来操作

//问题已经被发现,我TMD就是个天才,sum是个全局变量,在递归的时候,已经变不回来 //了!

{

if(pos == 15)

{

if(sonSum == 0 && A[14] == 1 && collectArray() == 5)

{

counting++;

for(int i =0;i<15;++i)

cout << A[i] << " ";

cout << endl;

return;

}

}else{

//if(collectArray() <= 5)

A[pos] = 0;

sonSum *= 2;

enumAll(pos+1,sonSum);

A[pos] = 1;

sonSum = sonSum / 2;

sonSum -= 1;

enumAll(pos+1,sonSum);

return;

//}

/*if( <= 10)

{

A[pos] = 1;

enuAll(pos+1);

A[pos] = 0;

enumAll(pos+1);

}*/

}

}

int main()

{

for(int i =0;i<15;++i)

{

A[i] = -1;

}

enumAll(0,sum);

cout << counting << endl;

return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值