您的位置:首页 > 其它

用程序解决生活中的“选择困难症”

2017-05-08 22:39 218 查看
今天和大家分享一个有趣的程序,博主编写这个程序是为了用程序帮我们做出生活中的那些困难的选择。

某参观团按以下条件限制从A、B、C、D、E五个地方中选定若干参观点:

如去A则必须去B;
D、E两地只能去一地;
B、C两地只能去一地;
C、D两地都去或都不去;
若去E地,A、D也必去。

问该团最多能去几个地方?是哪几个地方?

分析:

用变量a, b, c, d, e 表示五个地点。变量的值为1,则表示去;变量的值为0,则表示不去。
根据题意可写出表达式:
          a+b==2 || a==0;
d+e != 2;
b+c != 2;
c+d==0 || c+d==2;
e+a+d==3 || e==0.

程序:
#include <stdio.h>

int main()
{
int a, b, c, d, e, count = 0, num, max = 0, ccount = 0, i;
int array[5][6] = {0};

for (a = 1; a >= 0; a--)    //穷举所有情况
for (b = 1; b >= 0; b--)
for (c = 1; c >= 0; c--)
for (d = 1; d >= 0; d--)
for (e = 1; e >= 0; e--)
{
if ((a+b == 2 || a == 0) &&
d+e != 2 &&
b+c != 2 &&
(c+d == 0 || c+d == 2) &&
(e+a+d == 3 || e == 0))    //符合条件的情况
{
count++;    //计数
num = a+b+c+d+e;    //计算能去几个地方
*(*(array + count)) = num;    //二维数组每一行存储一种情况
*(*(array + count)+1) = a;
*(*(array + count)+2) = b;
*(*(array + count)+3) = c;
*(*(array + count)+4) = d;
*(*(array + count)+5) = e;    //每行的第一列存储该情况能去几个地方,每行二至六列存储该情况a~f对应的值
if (num > max)    //比较,得出最多能去几个地方
{
max = num;

4000
}
}
}

printf("\nThey can visit %d places at most.\n\n", max);
for (i = 0; i < 5; i++)
{
if (max == *(*(array+i)))    //若此情况为 去的地方最多 的情况,打印
{
printf("plan %d :\n", ++ccount);
printf("They will%s go A.\n", *(*(array+i)+1) ? "" : " not");
printf("They will%s go B.\n", *(*(array+i)+2) ? "" : " not");
printf("They will%s go C.\n", *(*(array+i)+3) ? "" : " not");
printf("They will%s go D.\n", *(*(array+i)+4) ? "" : " not");
printf("They will%s go E.\n", *(*(array+i)+5) ? "" : " not");
printf("\n");
}
}

return 0;
}


结果:



这样的程序是不是既实用又有趣呢?
今天就到这里啦,大家晚安!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐