一个朴素的24点算法
来源:互联网 发布:网络整合营销推广 编辑:程序博客网 时间:2024/06/02 23:57
#include <stdio.h>#include <iostream>#include <stack>#include <vector> #define OPER_ADD 0x00000001#define OPER_SUB 0x00000002#define OPER_MUL 0x00000004#define OPER_DIV 0x00000008#define OPT_NUM 3 using namespace std;int org[4]; vector<int> A;stack<vector<int> > mystack; int listnum(void){ vector<int> B; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(i!=j) { for(int k=0;k<4;k++) { if((k!=j) && (k!=i)) { for(int h=0;h<4;h++) { if((h!=j) && (h!=k) && (h!=i)) { B.push_back(org[i]); B.push_back(org[j]); B.push_back(org[k]); B.push_back(org[h]); mystack.push(B); B.clear(); } } } } } } } return 0; } int tfpoint(int num,int sum, unsigned int *optflag,int optnum){ if(num==1) { if(A[num-1]==sum) { char opt1,opt2,opt3; if(*optflag & OPER_ADD) opt1='+'; if(*optflag & OPER_SUB) opt1='-'; if(*optflag & OPER_MUL) opt1='*'; if(*optflag & OPER_DIV) opt1='/'; if(*optflag & (OPER_ADD<<4)) opt2='+'; if(*optflag & (OPER_SUB<<4)) opt2='-'; if(*optflag & (OPER_MUL<<4)) opt2='*'; if(*optflag & (OPER_DIV<<4)) opt2='/'; if(*optflag & (OPER_ADD<<8)) opt3='+'; if(*optflag & (OPER_SUB<<8)) opt3='-'; if(*optflag & (OPER_MUL<<8)) opt3='*'; if(*optflag & (OPER_DIV<<8)) opt3='/'; printf("((%d%c%d)%c%d)%c%d\n",A[0],opt3,A[1],opt2,A[2],opt1,A[3]); } return 0; } int ret=0; unsigned int opt1,opt2,opt3,opt4; opt1 = *optflag; opt2 = *optflag; opt3 = *optflag; opt4= *optflag; //add ret=sum-A[num-1]; opt1 |= OPER_ADD << ((OPT_NUM-optnum)*4); tfpoint(num-1,ret,&opt1,optnum-1); //sub ret=sum+A[num-1]; opt2 |= OPER_SUB << ((OPT_NUM-optnum)*4); tfpoint(num-1,ret,&opt2,optnum-1); //mul if(A[num-1]!=0) { if((sum % A[num-1]) == 0) { ret=sum/A[num-1]; opt3 |= OPER_MUL << ((OPT_NUM-optnum)*4); tfpoint(num-1,ret,&opt3,optnum-1); } } //div ret=sum*A[num-1]; opt4 |= OPER_DIV << ((OPT_NUM-optnum)*4); tfpoint(num-1,ret,&opt4,optnum-1); return 1;}int main(){ int data1,data2,data3,data4; printf("请输入第一个数:\n"); cin >> data1; printf("请输入第二个数: \n"); cin >> data2; printf("请输入第三个数: \n"); cin >> data3; printf("请输入第四个数: \n"); cin >> data4; org[0]=data1; org[1]=data2; org[2]=data3; org[3]=data4; unsigned int optflag=0; listnum(); int * data; while(!mystack.empty()) { A =mystack.top(); mystack.pop(); tfpoint(A.size(),24,&optflag,3); } return 0;}