pku grid 2787 24点问题

#include <iostream> #include <cmath> using namespace std; double number[4]; /* 把这四个数看做一个集合 Ex: A = {1, 2, 3, 4}; 取出任意两个数,例如:1+2 = 3, 1-2 = -1, 2-1 = 1, 1/2 = 0.5, 2/1 = 2, 1*2 = 2; 从而得到: A= {3,3,4}, {-1,3,4}, {1,3,4}, {0.5,3,4}, {2,3,4}, {2,3,4}; . . . 从而不断划归为子问题 */ bool solve(int left) { if(left == 1) { if(fabs(number[0] - 24.0) < 1E-6) return true; return false; } for(int i = 0; i < left; ++i) for(int j = i+1; j < left; ++j) { double a = number[i]; double b = number[j]; number[i] = a + b; number[j] = number[left-1]; if(solve(left-1)) return true; number[i] = a - b; number[j] = number[left-1]; if(solve(left-1)) return true; number[i] = b- a; number[j] = number[left-1]; if(solve(left-1)) return true; number[i] = a * b; number[j] = number[left-1]; if(solve(left-1)) return true; if(b) { number[i] = a / b; number[j] = number[left-1]; if(solve(left-1)) return true; } if(a) { number[i] = b / a; number[j] = number[left-1]; if(solve(left-1)) return true; } number[i] = a; number[j] = b; } return false; } int main() { while(scanf("%lf%lf%lf%lf", &number[0], &number[1], &number[2], &number[3]) && !(number[0] == 0 && number[1] == 0 && number[2] == 0 && number[3] == 0)) { if(solve(4)) printf("YES/n"); else printf("NO/n"); } return 0; }

你可能感兴趣的:(include)