1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #include<iostream> #include<algorithm> #include<string> #include<set> #include<vector> #include<cctype> #include<map> using namespace std; const string sign[]={"*","+","-",""}; set<string> ans; map<char,int> dict; bool cal(string s){ int t=0,p=0,q=0; vector<int> num,sg; while(1){ int num0=0,sg0=0; while(isdigit(s[p])) num0*=10,num0+=s[p++]-'0'; num.push_back(num0); if(s[p]=='=') break; sg0=dict[s[p++]]; sg.push_back(sg0); ++q; } for(int i=0;i<sg.size();++i){ if(sg[i]==1){ num[i+1]*=num[i]; num.erase(num.begin()+i); sg.erase(sg.begin()+i); --i; } } t=num[0]; for(int i=0;i<sg.size();i++){ if(sg[i]==2) t+=num[i+1]; else t-=num[i+1]; } return t==2000; } void dfs(string s,int pos,bool flag){ if(pos==s.size()-1){ if(cal(s)) ans.insert(s); return; } for(int i=0;i<4;++i){ if(!flag&&i==3) continue; string s0=s; if(s[pos]!='0') dfs(s0.insert(pos,sign[i]),i==3?pos+1:pos+2,true); else dfs(s0.insert(pos,sign[i]),i==3?pos+1:pos+2,i==3); } return; } int main(){ ios::sync_with_stdio(false); int t=0; string s; dict['*']=1,dict['+']=2,dict['-']=3; while(cin>>s){ ans.clear(); if(s[0]=='=') break; dfs(s,1,s[0]!='0'); cout<<"Problem "<<++t<<endl; if(!ans.size()||s=="2000=") cout<<" IMPOSSIBLE"<<endl; else for(set<string>::iterator it=ans.begin();it!=ans.end();++it) cout<<" "<<*it<<endl; } return 0; }
|