10344 - 23 out of 5

来源:互联网 发布:怎么学会c语言 编辑:程序博客网 时间:2024/05/22 14:31

题目:10344 - 23 out of 5


题目大意:给出五个数,问能否通过上述的公式就是包含加减乘来产生23.


解题思路:生成五个数所有的排列,然后再dfs()加减乘,判断是否能达到23,可以直接退出,不能的话就继续dfs。注意:stl里面给的next_permutation()是需要数组s本身有序这个前提的,否则生成的排序会不全。


#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int N = 5;int s[N];const char op[3] = {'+', '-', '*'};bool flag;void handle (int sum, int deep) {if (deep == N - 1) {if (sum == 23)flag = 1;return ;}for (int i = 0; i < 3; i++ ) {switch(op[i]) {case '+':handle (sum + s[deep + 1], deep + 1);break;case '-':handle (sum - s[deep + 1], deep + 1);break;case '*':handle (sum * s[deep + 1], deep + 1);break;}if (flag)return;}}int main () {while (scanf("%d%d%d%d%d", &s[0], &s[1], &s[2], &s[3], &s[4])) {if (!s[0]  && !s[1] && !s[2] && !s[3] && !s[4])break;flag = 0;sort(s, s + N);do {handle (s[0], 0);if (flag)break;}while (next_permutation(s, s + N));if (flag)printf("Possible\n");elseprintf("Impossible\n");}return 0;}


0 0
原创粉丝点击