P1236 算24点

题目链接

 

 

 1 #include <bits/stdc++.h>
 2 # define LL long long
 3 using namespace std;
 4 
 5 bool dfs(vector<int> &num, vector<string> &res){
 6     if(num.size()==1) {
 7         if(num[0]==24) return true;
 8         return false;
 9     }
10 
11     string tmp;
12     vector<int> nexted;
13     for(int i=0;i<num.size()-1;++i){
14 
15         for(int j=i+1;j<num.size();++j){
16             int a=num[i];
17             int b=num[j];
18 
19             if(a<b) swap(a,b);
20 
21             nexted.clear();
22             for(int k=0;k<num.size();++k){
23                 if(k==i || k==j) continue;
24                 nexted.push_back(num[k]);
25             }
26             nexted.push_back(a+b);
27             tmp=to_string(a)+"+"+to_string(b)+"="+to_string(a+b);
28             res.push_back(tmp);
29             if(dfs(nexted,res)) return true;
30             res.pop_back();
31 
32             nexted.clear();
33             for(int k=0;k<num.size();++k){
34                 if(k==i || k==j) continue;
35                 nexted.push_back(num[k]);
36             }
37             nexted.push_back(a-b);
38 
39             tmp=to_string(a)+"-"+to_string(b)+"="+to_string(a-b);
40             res.push_back(tmp);
41             if(dfs(nexted,res)) return true;
42             res.pop_back();
43 
44             nexted.clear();
45             vector<int> tmpv;
46             for(int k=0;k<num.size();++k){
47                 if(k==i || k==j) continue;
48                 nexted.push_back(num[k]);
49             }
50             nexted.push_back(a*b);
51             tmp=to_string(a)+"*"+to_string(b)+"="+to_string(a*b);
52             res.push_back(tmp);
53             if(dfs(nexted,res)) return true;
54             res.pop_back();
55 
56             if(b!=0 &&  a%b==0){
57                 nexted.clear();
58                 for(int k=0;k<num.size();++k){
59                     if(k==i || k==j) continue;
60                     nexted.push_back(num[k]);
61                 }
62                 nexted.push_back(a/b);
63                 tmp=to_string(a)+"/"+to_string(b)+"="+to_string(a/b);
64                 res.push_back(tmp);
65                 if(dfs(nexted,res)) return true;
66                 res.pop_back();
67             }
68         }
69     }
70     return false;
71 }
72 
73 int main(){
74     vector<int> num(4,0);
75     for(int i=0;i<4;++i){
76         int t;
77         scanf("%d", &t);
78         num[i]=t;
79     }
80     vector<string> res;
81     bool r=dfs(num,res);
82     if(!r){
83         printf("No answer!\n");
84         return 0;
85     }
86     for(auto &s:res){
87         cout<<s<<"\n";
88     }
89     return 0;
90 }

 

posted @ 2020-02-02 20:51  feibilun  阅读(203)  评论(0编辑  收藏  举报