fork download
  1. // 若干修正
  2. #include <iostream>
  3. #include <sstream>
  4. #include <vector>
  5. #include <map>
  6. #include <algorithm>
  7. #include <functional>
  8.  
  9. using namespace std;
  10.  
  11. template <class N>
  12. struct calculator {
  13. typedef string op_type;
  14. typedef map<op_type, function<N(N,N)> > op_map;
  15.  
  16. vector<N> elems;
  17. vector<op_type> ops;
  18.  
  19. op_map s_opmap = {
  20. {"+", plus<N>()}, {"-", minus<N>()},
  21. {"/", divides<N>()}, {"*", multiplies<N>()} };
  22.  
  23. vector<vector<op_type>> prio = { {"*","/"}, {"+","-"} };
  24.  
  25. calculator(vector<N>& e) : elems(e) {}
  26.  
  27. bool validate(){
  28. vector<N> cvals(elems);
  29. vector<op_type> cops(ops);
  30.  
  31. for( auto ops: prio )
  32. for( int i = 0; i < cops.size(); i++ )
  33. if( any_of( ops.begin(), ops.end(),
  34. bind( equal_to<op_type>(), cops[i], placeholders::_1 ) )
  35. ){
  36. cvals[i] = s_opmap[ cops[i] ](cvals[i],cvals[i+1]);
  37.  
  38. cvals.erase(cvals.begin() + i+1);
  39. cops.erase(cops.begin() + i--);
  40. }
  41.  
  42. return ( cvals.size() == 2 && cvals.back() == cvals.front() );
  43. }
  44.  
  45. void calculate(){
  46. this->ops = vector<op_type>();
  47. bool found = next_comb();
  48.  
  49. cout << elems[0] << " "; // head
  50. for( size_t i = 1; i < elems.size() -1; i++ )
  51. found && (cout << ops[i-1]), cout << " " << elems[i] << " ";
  52.  
  53. cout << (found ? "= " : "has no op-combs to be ") << elems.back() << endl;
  54. }
  55.  
  56. bool next_comb(){
  57. return ( ops.size() == (elems.size() -2) ) ? validate() :
  58. any_of(s_opmap.begin(),s_opmap.end(),[&]( typename op_map::value_type& o ){
  59. ops.push_back(o.first);
  60. return next_comb() || (ops.pop_back(), false);
  61. });
  62. }
  63. };
  64.  
  65. template < class num_type >
  66. int main_deleg(){
  67. for( string line; getline(cin,line); ){
  68. replace (line.begin(), line.end(), ':', ' ');
  69.  
  70. istringstream iss(line);
  71. vector<num_type> list;
  72.  
  73. for( num_type n; ! (iss >> n).fail(); list.push_back(n) );
  74.  
  75. if( list.size() > 1 )
  76. calculator<num_type>(list).calculate();
  77. else
  78. cout << line << ": invalid line. skip. " << endl;
  79. }
  80. return 0;
  81. }
  82.  
  83. int main(){ return main_deleg<double>(); }
  84.  
  85.  
Success #stdin #stdout 0s 3496KB
stdin
1 1 1 1 : 6
1 2 3 4 5 : 10
1 2 3 4 5 6 7 8 :  10
stdout
1  1  1  1 has no op-combs to be 6
1 + 2 + 3 * 4 - 5 = 10
1 * 2 * 3 * 4 - 5 + 6 - 7 - 8 = 10