例4-12 穷举算法-搬砖
男人三块、女人两块、小孩两人一块,45人搬45块、求方案
程序核心——多for语句镶嵌
1程序
#include<stdio.h>
int main()
{
int child,men,women;
for(men=0;men<=45;men++)
for(women=0;women<=45;women++)
for(child=0;child<=45;child++)
if(men+women+child==45&&men*3+women*2+child*0.5==45)
printf("men=%d,women=%d,child=%d
",men,women,child);
return 0;
}
2程序
#include<stdio.h>
int main()
{
int child,men,women;
for(men=0;men<=15;men++)
for(women=0;women<=22;women++)
{
child=45-women-men;
if(men*3+women*2+child*0.5==45)
printf("men=%d,women=%d,child=%d
",men,women,child);
}
return 0;
}
结果
men=0,women=15,child=30
men=3,women=10,child=32
men=6,women=5,child=34
men=9,women=0,child=36
--------------------------------
Process exited after 0.3281 seconds with return value 0
请按任意键继续. . .
分析
重点:解决问题有多种算法,我们追求的更快更简单的