24 Point Game Algorithm topic description
Problem Description: Give 4 1-10 numbers, pass the subtraction, get the number 24 even if the victory
Input:
4 digits in 1-10. [number allows repetition, test case guarantees no exception number]
Output:
True or False Enter a description:
Enter 4 int integer output Description:
Returns whether can get 24 points, can output true, cannot output false input Example:
7 2 1 output Example:
True
Answer code:
#include <iostream> #include <string> #include <cstring> #include <algorithm> #include <
Fstream> #define N 4 using namespace std;
int flag=0;
int num[n];
void Solvebydfs (int index,int result,int num[]) {if (result==24) {flag=1;
return;
if (Result > | | index>=4) return; for (int choose=0; choose<4; choose++) {switch (choose) {Case 0:SOLVEBYDFS (Ind
Ex+1,result+num[index],num);
Break
Case 1:solvebydfs (Index+1,result-num[index],num);
Break
Case 2:solvebydfs (Index+1,result*num[index],num);
Break
Case 3:solvebydfs (Index+1,result/num[index],num);
Break
} if (flag) return;
int main () {int test=0;
while (Cin>>num[0]>>num[1]>>num[2]>>num[3]) {flag=0;
test=0; Sort(NUM,NUM+4);
do {Solvebydfs (0,test,num);
while (Next_permutation (num,num+4));
if (flag) cout<< "true" <<endl;
else cout<< "false" <<endl;
return 0; }