286
社区成员




3
块,女人一人搬2
块,小孩两人搬1
块。如果想用n
人正好搬n
块砖,问有多少种搬法?输入在一行中给出一个正整数n
。
输出在每一行显示一种方案,按照"men = cnt_m, women = cnt_w, child = cnt_c
"的格式,输出男人的数量cnt_m
,女人的数量cnt_w
,小孩的数量cnt_c
。请注意,等号的两侧各有一个空格,逗号的后面也有一个空格。
如果找不到符合条件的方案,则输出"None
"
45
men = 0, women = 15, child = 30
men = 3, women = 10, child = 32
men = 6, women = 5, child = 34
men = 9, women = 0, child = 36
首先,设置一个函数solve_brick(int n)函数接受一个参数n,在函数内部利用for循环的嵌套枚举所有可能的男人、女人、小孩的数量,计算是否满足总数为n,且积木数量恰好为n的条件。函数如下:
void solve_brick(int n) {
int cnt_men, cnt_women, cnt_child;
int found = 0;
for (cnt_men = 0; cnt_men <= n; cnt_men++) {
for (cnt_women = 0; cnt_women <= n; cnt_women++) {
for (cnt_child = 0; cnt_child <= n; cnt_child++) {
if ((cnt_men * 3 + cnt_women * 2 + cnt_child * 0.5) == n && cnt_men + cnt_women + cnt_child == n) {
printf("men = %d, women = %d, child = %d\n", cnt_men, cnt_women, cnt_child);
found = 1;
}
}
}
}
if (!found) {
printf("None\n");
}
}
然后,输入n,将n,代入函数作为参数即可,完整代码如下:
#include <stdio.h>
void solve_brick(int n) {
int cnt_men, cnt_women, cnt_child;
int found = 0;
for (cnt_men = 0; cnt_men <= n; cnt_men++) {
for (cnt_women = 0; cnt_women <= n; cnt_women++) {
for (cnt_child = 0; cnt_child <= n; cnt_child++) {
if ((cnt_men * 3 + cnt_women * 2 + cnt_child * 0.5) == n && cnt_men + cnt_women + cnt_child == n) {
printf("men = %d, women = %d, child = %d\n", cnt_men, cnt_women, cnt_child);
found = 1;
}
}
}
}
if (!found) {
printf("None\n");
}
}
int main() {
int n;
scanf("%d", &n);
solve_brick(n);
return 0;
}
运用了穷举算法,还可以分析一下其特点、不足和改进。