[关闭]
@songpfei 2016-01-05T14:54:09.000000Z 字数 20494 阅读 1787

24点游戏问题

OJ_算法


1. 题目描述

问题描述:给出4个1-10的数字,通过加减乘除,得到数字为24就算胜利
输入:4个1-10的数字。[数字允许重复,测试用例保证无异常数字]
输出:True or False

2. 问题求解(穷举法)

  利用穷举法,列出所有可能的表达式,然后计算表达式的值,问题便求解。
此问题可以分解为两步:
1. 列出所有可能的表达式
2. 计算法表达式(四则混合运算)的值

2.1 列出所有可能的表达式

表达式由输出的四个数字(1~10)、3个加减乘除(“+”、“-”、“*”、“/")运算符以及括号组成。
分析所有组合(情况数):
1. 四个数字的所有排序:4*3*2=24
2. 四个数字中间的运算符的所有排列(由于运算符可以重复):4*4*4=64;
3. 添加括号分为以下三种情况:eg:a+b*c-d

类型 实例 数量(种)
无括号 a+b*c-d 1
1个括号 (a+b)*c-d;a+(b*c)-d;a+b*(c-d);(a+b*c)-d;a+(b*c-d); 5
2个括号 (a+b)*(c-d) 1

注:2个括号的其他类型通过去括号转化为一个括号类型

综上所述:所有表达式的排列为:24*64*(1+5+1)=10752(其中可能有重复)
代码实现:

  1. //1.全排列:用递归的思想求出全排列
  2. void swap(int &a, int &b)//交换连个元素
  3. {
  4. int tem;
  5. tem = a;
  6. a = b;
  7. b = tem;
  8. }
  9. //计算所有操作数的全排列
  10. void CalAllPermutation(int *a, int first, int length, vector<vector<string>>&permutation)
  11. {
  12. if (first == length - 1)//如果递归到深层时,到最后交换的元素即时最后一个元素时就打印出来
  13. {
  14. vector<string> permu(length);
  15. char itoa_buffer[64];
  16. for (int i = 0; i < length; i++)
  17. {
  18. sprintf(itoa_buffer, "%d", a[i]);
  19. permu[i] = string(itoa_buffer);
  20. }
  21. permutation.push_back(permu);
  22. }
  23. else
  24. {
  25. for (int i = first; i < length; i++)
  26. {//循环遍历使得当前位置后边的每一个元素都和当前深度的第一个元素交换一次
  27. swap(a[first], a[i]);//使得与第一个元素交换
  28. CalAllPermutation(a, first + 1, length, permutation);//深入递归,此时已确定前边的元素,处理后边子序列的全排列形式。
  29. swap(a[first], a[i]);//恢复交换之前的状态
  30. }
  31. }
  32. }
  33. //计算所有运算符的组合
  34. void CalOpSymbolCombination(string&sym, int ope_bit, int n, vector<string>&symbol)
  35. {
  36. if (ope_bit == n)
  37. {
  38. symbol.push_back(sym);
  39. return;
  40. }
  41. for (int i = 0; i < 4; i++)
  42. {
  43. switch (i)
  44. {
  45. case 0:
  46. sym[ope_bit] = '+';
  47. break;
  48. case 1:
  49. sym[ope_bit] = '-';
  50. break;
  51. case 2:
  52. sym[ope_bit] = '*';
  53. break;
  54. case 3:
  55. sym[ope_bit] = '/';
  56. break;
  57. default:
  58. break;
  59. }
  60. CalOpSymbolCombination(sym, ope_bit + 1, n, symbol);
  61. }
  62. }

2.2. 计算法表达式(四则混合运算)的值

2.2.1将中缀表达式变为后缀表达式

我们把平时所用的标准四则运算表达式,即“9+(3-1)×3+10÷2”叫做中缀表达式。因为所有的运算符号都在两数字的中间。

  中缀表达式 “9+(3-1)×3+10÷2” 转化为后缀表达式 “9 3 1 - 3 * + 10 2 / +” 。

规则中缀表达式转后缀表达式的方法:
1.遇到操作数:直接输出(添加到后缀表达式中)
2.栈为空时,遇到运算符,直接入栈
3.遇到左括号:将其入栈
4.遇到右括号:执行出栈操作,并将出栈的元素输出,直到弹出栈的是左括号,左括号不输出。
5.遇到其他运算符:加减乘除:弹出所有优先级大于或者等于该运算符的栈顶元素,然后将该运算符入栈
6.最终将栈中的元素依次出栈,输出。

代码实现(中缀表达式转后缀表达式):

  1. // 2. 中缀表达式变后缀表达式并计算值
  2. static char symbolPriority[4][4] = {
  3. /* 符号优先级表 /* '+' '-' '*' '/' */
  4. /* '+' */{ '=', '=', '<', '<',},
  5. /* '-' */{ '=', '=', '<', '<',},
  6. /* '*' */{ '>', '>', '=', '=',},
  7. /* '/' */{ '>', '>', '=', '=' } };
  8. vector<string> InfixToPostfixExpression(const string &infixExpression)
  9. {
  10. size_t i = 0;
  11. vector<string> suffix_expression;
  12. stack<char> symbol_stack;//符号栈
  13. char ch = infixExpression[i++];
  14. while (i <= infixExpression.size())
  15. {
  16. if (isdigit(ch))//1.遇到数字,直接输出
  17. {
  18. string digit;
  19. while (isdigit(ch))
  20. {
  21. digit.push_back(ch);
  22. ch = infixExpression[i++];
  23. }
  24. suffix_expression.push_back(digit);
  25. }
  26. else
  27. {
  28. if (symbol_stack.empty()||ch=='('||symbol_stack.top()=='(')//2.遇到符号:栈为空或符号为'('或栈顶为‘(',符号直接入栈
  29. {
  30. symbol_stack.push(ch);
  31. ch = infixExpression[i++];
  32. }
  33. else if (ch == ')')//3. 遇到右括号,弹出所有栈中符号直到左括号并输出(左括号不输出)
  34. {
  35. while (symbol_stack.top()!='(')
  36. {
  37. string a(1, '#');
  38. a[0] = symbol_stack.top();
  39. symbol_stack.pop();
  40. suffix_expression.push_back(a);
  41. }
  42. symbol_stack.pop();//弹出左括号,不输出
  43. ch = infixExpression[i++];
  44. }
  45. else
  46. {
  47. while (!symbol_stack.empty())
  48. {
  49. char sym_priority = CompareSymbolPriorityPost(symbol_stack.top(), ch);
  50. if (sym_priority == '>' || sym_priority == '=')//4.弹出优先级大于等于ch的所有符号
  51. {
  52. string a(1, '#');
  53. a[0] = symbol_stack.top();
  54. symbol_stack.pop();
  55. suffix_expression.push_back(a);
  56. }
  57. else
  58. break;
  59. }
  60. symbol_stack.push(ch);//压入符号
  61. ch = infixExpression[i++];
  62. }
  63. }
  64. }
  65. while (!symbol_stack.empty())
  66. {
  67. string a(1, '#');
  68. a[0] = symbol_stack.top();
  69. symbol_stack.pop();
  70. suffix_expression.push_back(a);
  71. }
  72. return suffix_expression;
  73. }
  74. char CompareSymbolPriorityPost(char sym1, char sym2)//中缀变后缀比较符号优先级
  75. {
  76. int index1 = IndexOfSymbol(sym1);
  77. int index2 = IndexOfSymbol(sym2);
  78. return symbolPriority[index1][index2];
  79. }
  80. int IndexOfSymbol(char sym)//符号优先级索引
  81. {
  82. int index;
  83. switch (sym)
  84. {
  85. case '+':
  86. index = 0;
  87. break;
  88. case '-':
  89. index = 1;
  90. break;
  91. case '*':
  92. index = 2;
  93. break;
  94. case '/':
  95. index = 3;
  96. break;
  97. case '(':
  98. index = 4;
  99. break;
  100. case ')':
  101. index = 5;
  102. break;
  103. case '=':
  104. index = 6;
  105. break;
  106. default:
  107. break;
  108. }
  109. return index;
  110. }

直接计算中缀表达是的值:

  1. //运算符的优先关系比对表
  2. static char SymbolRelation[7][7] = {
  3. //'+', '-', '*', '/', '(', ')', '=' //运算符2
  4. { '>', '>', '<', '<', '<', '>', '>' }, //'+' //运算符1
  5. { '>', '>', '<', '<', '<', '>', '>' }, //'-'
  6. { '>', '>', '>', '>', '<', '>', '>' }, //'*'
  7. { '>', '>', '>', '>', '<', '>', '>' }, //'/'
  8. { '<', '<', '<', '<', '<', '=', '>' }, //'('
  9. { '>', '>', '>', '>', '=', '>', '>' }, //')'
  10. { '<', '<', '<', '<', '<', ' ', '=' } };//'='
  11. double CalResultBySuffixExpression(string &infixExpresion)
  12. {
  13. stack<char> symbol_stack;//符号栈
  14. stack<double> suffix_expression;//后缀表达式
  15. char ch;
  16. int i = 0;
  17. infixExpresion += '=';
  18. symbol_stack.push('=');
  19. ch = infixExpresion[i++];
  20. while (ch != '=' || symbol_stack.top() != '=')
  21. {
  22. if (isdigit(ch))//数字,直接输出
  23. {
  24. int ope_data = 0;
  25. while (isdigit(ch))
  26. {
  27. ope_data = 10 * ope_data + ch - '0';//将字符串操作数转化为整数
  28. ch = infixExpresion[i++];
  29. }
  30. suffix_expression.push(ope_data);
  31. }
  32. else
  33. {
  34. switch (CompareSymbolPriority(symbol_stack.top(), ch))
  35. {
  36. case '<'://栈顶符号优先级低:继续压入符号进栈
  37. symbol_stack.push(ch);
  38. ch = infixExpresion[i++];
  39. break;
  40. case '='://括号配对:弹出栈顶括号,并丢弃该括号
  41. symbol_stack.pop();
  42. ch = infixExpresion[i++];
  43. break;
  44. case '>'://栈顶优先级高
  45. char sym_top = symbol_stack.top();
  46. symbol_stack.pop();
  47. double num2 = suffix_expression.top();
  48. suffix_expression.pop();
  49. double num1 = suffix_expression.top();
  50. suffix_expression.pop();
  51. double sub_result = CalSubExpressionResult(num1, num2, sym_top);
  52. suffix_expression.push(sub_result);
  53. break;
  54. }
  55. }
  56. }
  57. return suffix_expression.top();//返回后缀表达式
  58. }
  59. char CompareSymbolPriority(char sym1, char sym2)//比较符号优先级,直接计算值
  60. {
  61. int index1 = IndexOfSymbol(sym1);
  62. int index2 = IndexOfSymbol(sym2);
  63. return SymbolRelation[index1][index2];
  64. }
  65. int IndexOfSymbol(char sym)//符号优先级索引
  66. {
  67. int index;
  68. switch (sym)
  69. {
  70. case '+':
  71. index = 0;
  72. break;
  73. case '-':
  74. index = 1;
  75. break;
  76. case '*':
  77. index = 2;
  78. break;
  79. case '/':
  80. index = 3;
  81. break;
  82. case '(':
  83. index = 4;
  84. break;
  85. case ')':
  86. index = 5;
  87. break;
  88. case '=':
  89. index = 6;
  90. break;
  91. default:
  92. break;
  93. }
  94. return index;
  95. }
  96. double CalSubExpressionResult(double a, double b, char symbol)
  97. {
  98. double result = 0.0;
  99. switch (symbol)
  100. {
  101. case '+':
  102. result = a + b;
  103. break;
  104. case '-':
  105. result = a - b;
  106. break;
  107. case '*':
  108. result = a*b;
  109. break;
  110. case '/':
  111. result = a / b;
  112. break;
  113. default:
  114. break;
  115. }
  116. return result;
  117. }

2.2.2 计算后缀表达式的值

后缀表达式计算结果

规则:从左到右遍历表达式的每个数字和符号,遇到是数字就进栈,遇到是符号,就将处于栈顶两个数字出栈,进行运算,运算结果进栈,一直到最终获得结果。(初始化一个空栈,此栈用来对要运算的数字进行使用)
代码实现:

  1. double CalSubExpressionResult(double a, double b, char symbol)
  2. {
  3. double result = 0.0;
  4. switch (symbol)
  5. {
  6. case '+':
  7. result = a + b;
  8. break;
  9. case '-':
  10. result = a - b;
  11. break;
  12. case '*':
  13. result = a*b;
  14. break;
  15. case '/':
  16. result = a / b;
  17. break;
  18. default:
  19. break;
  20. }
  21. return result;
  22. }
  23. //3. 计算后缀表达式的值
  24. double CalPostfixExpressionValue(const vector<string>& postfixExpression)
  25. {
  26. stack<double> exp_data;
  27. for (size_t i=0;i<postfixExpression.size();i++)
  28. {
  29. if(isdigit(postfixExpression[i][0]))
  30. {
  31. double data=atof(postfixExpression[i].c_str());
  32. exp_data.push(data);
  33. }
  34. else
  35. {
  36. double num1,num2;
  37. num2 = exp_data.top();
  38. exp_data.pop();
  39. num1 = exp_data.top();
  40. exp_data.pop();
  41. double temp_result= CalSubExpressionResult(num1,num2,postfixExpression[i][0]);
  42. exp_data.push(temp_result);
  43. }
  44. }
  45. return exp_data.top();
  46. }

3. 24点游戏(穷举法)代码实现(全)

  1. #include"Game24Points.h"
  2. #include<cstdio>
  3. #include<cctype>
  4. #include<string>
  5. #include<vector>
  6. #include<stack>
  7. #include <iostream>
  8. using namespace std;
  9. static void swap(int &a, int &b);//交换连个元素
  10. static void CalAllPermutation(int *a, int first, int length, vector<vector<string>>&permutation);
  11. static void CalOpSymbolCombination(string&sym, int ope_bit, int n, vector<string>&symbol);
  12. static int IndexOfSymbol(char sym);
  13. static char CompareSymbolPriority(char sym1, char sym2);//比较符号优先级
  14. static char CompareSymbolPriorityPost(char sym1, char sym2);//中缀变后缀比较符号优先级
  15. static std::vector<std::string> InfixToPostfixExpression(const std::string &infixExpression);
  16. static double CalSubExpressionResult(double a, double b, char symbol);
  17. static double CalResultBySuffixExpression(string &infixExpresion);
  18. static double CalPostfixExpressionValue(const vector<string>& postfixExpression);
  19. //运算符的优先关系比对表
  20. static char SymbolRelation[7][7] = {
  21. //'+', '-', '*', '/', '(', ')', '=' //运算符2
  22. { '>', '>', '<', '<', '<', '>', '>' }, //'+' //运算符1
  23. { '>', '>', '<', '<', '<', '>', '>' }, //'-'
  24. { '>', '>', '>', '>', '<', '>', '>' }, //'*'
  25. { '>', '>', '>', '>', '<', '>', '>' }, //'/'
  26. { '<', '<', '<', '<', '<', '=', '>' }, //'('
  27. { '>', '>', '>', '>', '=', '>', '>' }, //')'
  28. { '<', '<', '<', '<', '<', ' ', '=' } };//'='
  29. static char symbolPriority[4][4] = {
  30. /* 符号优先级表 /* '+' '-' '*' '/' */
  31. /* '+' */{ '=', '=', '<', '<',},
  32. /* '-' */{ '=', '=', '<', '<',},
  33. /* '*' */{ '>', '>', '=', '=',},
  34. /* '/' */{ '>', '>', '=', '=' } };
  35. bool Game24Points(int a, int b, int c, int d)
  36. {
  37. int data[4] = { a,b,c,d };
  38. vector<vector<string>> permutation;
  39. string sym(3, '=');
  40. vector<string> symbol;
  41. string infix_expression;//中缀表达式
  42. vector<string> postfix_expression;//后缀表达式
  43. double expression_result = 0.0;
  44. CalAllPermutation(data, 0, 4, permutation);//计算数字输入数字的全排列
  45. CalOpSymbolCombination(sym, 0, 3, symbol);//计算表达式中间三个符号的所有组合
  46. for (size_t i = 0; i < permutation.size(); i++)
  47. {
  48. for (size_t j = 0; j<symbol.size(); j++)
  49. {
  50. for (size_t k = 0; k < 7; k++)//添加括号
  51. {
  52. switch (k)
  53. {
  54. case 0://无括号类型
  55. infix_expression = permutation[i][0] + symbol[j][0] + permutation[i][1] + symbol[j][1] + permutation[i][2]
  56. + symbol[j][2] + permutation[i][3];
  57. break;
  58. case 1://(a+b)*c-d类型
  59. infix_expression = "(" + permutation[i][0] + symbol[j][0] + permutation[i][1] + ")" + symbol[j][1] + permutation[i][2]
  60. + symbol[j][2] + permutation[i][3];
  61. break;
  62. case 2://a+(b*c)-d类型
  63. infix_expression = permutation[i][0] + symbol[j][0] + "(" + permutation[i][1] + symbol[j][1] + permutation[i][2] + ")"
  64. + symbol[j][2] + permutation[i][3];
  65. break;
  66. case 3://a+b*(c-d)类型
  67. infix_expression = permutation[i][0] + symbol[j][0] + permutation[i][1] + symbol[j][1] + "(" + permutation[i][2]
  68. + symbol[j][2] + permutation[i][3] + ")";
  69. break;
  70. case 4://(a+b*c)-d类型
  71. infix_expression = "(" + permutation[i][0] + symbol[j][0] + permutation[i][1] + symbol[j][1] + permutation[i][2]
  72. + ")" + symbol[j][2] + permutation[i][3];
  73. break;
  74. case 5://a+(b*c-d)类型
  75. infix_expression = permutation[i][0] + symbol[j][0] + "(" + permutation[i][1] + symbol[j][1] + permutation[i][2]
  76. + symbol[j][2] + permutation[i][3] + ")";
  77. break;
  78. case 6://(a+b)*(c-d)类型
  79. infix_expression = "(" + permutation[i][0] + symbol[j][0] + permutation[i][1] + ")" + symbol[j][1] + "(" + permutation[i][2]
  80. + symbol[j][2] + permutation[i][3] + ")";
  81. break;
  82. default:
  83. break;
  84. }
  85. //expression_result = CalResultBySuffixExpression(infix_expression) - 24;
  86. postfix_expression=InfixToPostfixExpression(infix_expression);
  87. expression_result=CalPostfixExpressionValue(postfix_expression)-24;
  88. if (expression_result<0.001&&expression_result>(-0.001))
  89. {
  90. cout<<infix_expression<<endl;
  91. return true;
  92. }
  93. }
  94. }
  95. }
  96. return false;
  97. }
  98. //1.全排列:用递归的思想求出全排列
  99. void swap(int &a, int &b)//交换连个元素
  100. {
  101. int tem;
  102. tem = a;
  103. a = b;
  104. b = tem;
  105. }
  106. void CalAllPermutation(int *a, int first, int length, vector<vector<string>>&permutation)
  107. {
  108. if (first == length - 1)//如果递归到深层时,到最后交换的元素即时最后一个元素时就打印出来
  109. {
  110. vector<string> permu(length);
  111. char itoa_buffer[64];
  112. for (int i = 0; i < length; i++)
  113. {
  114. sprintf(itoa_buffer, "%d", a[i]);
  115. permu[i] = string(itoa_buffer);
  116. }
  117. permutation.push_back(permu);
  118. }
  119. else
  120. {
  121. for (int i = first; i < length; i++)
  122. {//循环遍历使得当前位置后边的每一个元素都和当前深度的第一个元素交换一次
  123. swap(a[first], a[i]);//使得与第一个元素交换
  124. CalAllPermutation(a, first + 1, length, permutation);//深入递归,此时已确定前边的元素,处理后边子序列的全排列形式。
  125. swap(a[first], a[i]);//恢复交换之前的状态
  126. }
  127. }
  128. }
  129. void CalOpSymbolCombination(string&sym, int ope_bit, int n, vector<string>&symbol)
  130. {
  131. if (ope_bit == n)
  132. {
  133. symbol.push_back(sym);
  134. return;
  135. }
  136. for (int i = 0; i < 4; i++)
  137. {
  138. switch (i)
  139. {
  140. case 0:
  141. sym[ope_bit] = '+';
  142. break;
  143. case 1:
  144. sym[ope_bit] = '-';
  145. break;
  146. case 2:
  147. sym[ope_bit] = '*';
  148. break;
  149. case 3:
  150. sym[ope_bit] = '/';
  151. break;
  152. default:
  153. break;
  154. }
  155. CalOpSymbolCombination(sym, ope_bit + 1, n, symbol);
  156. }
  157. }
  158. // 2. 中缀表达式变后缀表达式并计算值
  159. vector<string> InfixToPostfixExpression(const string &infixExpression)
  160. {
  161. size_t i = 0;
  162. vector<string> suffix_expression;
  163. stack<char> symbol_stack;//符号栈
  164. char ch = infixExpression[i++];
  165. while (i <= infixExpression.size())
  166. {
  167. if (isdigit(ch))//1.遇到数字,直接输出
  168. {
  169. string digit;
  170. while (isdigit(ch))
  171. {
  172. digit.push_back(ch);
  173. ch = infixExpression[i++];
  174. }
  175. suffix_expression.push_back(digit);
  176. }
  177. else
  178. {
  179. if (symbol_stack.empty()||ch=='('||symbol_stack.top()=='(')//2.遇到符号:栈为空或符号为'('或栈顶为‘(',符号直接入栈
  180. {
  181. symbol_stack.push(ch);
  182. ch = infixExpression[i++];
  183. }
  184. else if (ch == ')')//3. 遇到右括号,弹出所有栈中符号直到左括号并输出(左括号不输出)
  185. {
  186. while (symbol_stack.top()!='(')
  187. {
  188. string a(1, '#');
  189. a[0] = symbol_stack.top();
  190. symbol_stack.pop();
  191. suffix_expression.push_back(a);
  192. }
  193. symbol_stack.pop();//弹出左括号,不输出
  194. ch = infixExpression[i++];
  195. }
  196. else
  197. {
  198. while (!symbol_stack.empty())
  199. {
  200. char sym_priority = CompareSymbolPriorityPost(symbol_stack.top(), ch);
  201. if (sym_priority == '>' || sym_priority == '=')//4.弹出优先级大于等于ch的所有符号
  202. {
  203. string a(1, '#');
  204. a[0] = symbol_stack.top();
  205. symbol_stack.pop();
  206. suffix_expression.push_back(a);
  207. }
  208. else
  209. break;
  210. }
  211. symbol_stack.push(ch);//压入符号
  212. ch = infixExpression[i++];
  213. }
  214. }
  215. }
  216. while (!symbol_stack.empty())
  217. {
  218. string a(1, '#');
  219. a[0] = symbol_stack.top();
  220. symbol_stack.pop();
  221. suffix_expression.push_back(a);
  222. }
  223. return suffix_expression;
  224. }
  225. //3. 计算后缀表达式的值
  226. double CalPostfixExpressionValue(const vector<string>& postfixExpression)
  227. {
  228. stack<double> exp_data;
  229. for (size_t i=0;i<postfixExpression.size();i++)
  230. {
  231. if(isdigit(postfixExpression[i][0]))
  232. {
  233. double data=atof(postfixExpression[i].c_str());
  234. exp_data.push(data);
  235. }
  236. else
  237. {
  238. double num1,num2;
  239. num2 = exp_data.top();
  240. exp_data.pop();
  241. num1 = exp_data.top();
  242. exp_data.pop();
  243. double temp_result= CalSubExpressionResult(num1,num2,postfixExpression[i][0]);
  244. exp_data.push(temp_result);
  245. }
  246. }
  247. return exp_data.top();
  248. }
  249. double CalResultBySuffixExpression(string &infixExpresion)
  250. {
  251. stack<char> symbol_stack;//符号栈
  252. stack<double> suffix_expression;//后缀表达式
  253. char ch;
  254. int i = 0;
  255. infixExpresion += '=';
  256. symbol_stack.push('=');
  257. ch = infixExpresion[i++];
  258. while (ch != '=' || symbol_stack.top() != '=')
  259. {
  260. if (isdigit(ch))//数字,直接输出
  261. {
  262. int ope_data = 0;
  263. while (isdigit(ch))
  264. {
  265. ope_data = 10 * ope_data + ch - '0';//将字符串操作数转化为整数
  266. ch = infixExpresion[i++];
  267. }
  268. suffix_expression.push(ope_data);
  269. }
  270. else
  271. {
  272. switch (CompareSymbolPriority(symbol_stack.top(), ch))
  273. {
  274. case '<'://栈顶符号优先级低:继续压入符号进栈
  275. symbol_stack.push(ch);
  276. ch = infixExpresion[i++];
  277. break;
  278. case '='://括号配对:弹出栈顶括号,并丢弃该括号
  279. symbol_stack.pop();
  280. ch = infixExpresion[i++];
  281. break;
  282. case '>'://栈顶优先级高
  283. char sym_top = symbol_stack.top();
  284. symbol_stack.pop();
  285. double num2 = suffix_expression.top();
  286. suffix_expression.pop();
  287. double num1 = suffix_expression.top();
  288. suffix_expression.pop();
  289. double sub_result = CalSubExpressionResult(num1, num2, sym_top);
  290. suffix_expression.push(sub_result);
  291. break;
  292. }
  293. }
  294. }
  295. return suffix_expression.top();//返回后缀表达式
  296. }
  297. char CompareSymbolPriority(char sym1, char sym2)//比较符号优先级,直接计算值
  298. {
  299. int index1 = IndexOfSymbol(sym1);
  300. int index2 = IndexOfSymbol(sym2);
  301. return SymbolRelation[index1][index2];
  302. }
  303. char CompareSymbolPriorityPost(char sym1, char sym2)//中缀变后缀比较符号优先级
  304. {
  305. int index1 = IndexOfSymbol(sym1);
  306. int index2 = IndexOfSymbol(sym2);
  307. return symbolPriority[index1][index2];
  308. }
  309. int IndexOfSymbol(char sym)//符号优先级索引
  310. {
  311. int index;
  312. switch (sym)
  313. {
  314. case '+':
  315. index = 0;
  316. break;
  317. case '-':
  318. index = 1;
  319. break;
  320. case '*':
  321. index = 2;
  322. break;
  323. case '/':
  324. index = 3;
  325. break;
  326. case '(':
  327. index = 4;
  328. break;
  329. case ')':
  330. index = 5;
  331. break;
  332. case '=':
  333. index = 6;
  334. break;
  335. default:
  336. break;
  337. }
  338. return index;
  339. }
  340. double CalSubExpressionResult(double a, double b, char symbol)
  341. {
  342. double result = 0.0;
  343. switch (symbol)
  344. {
  345. case '+':
  346. result = a + b;
  347. break;
  348. case '-':
  349. result = a - b;
  350. break;
  351. case '*':
  352. result = a*b;
  353. break;
  354. case '/':
  355. result = a / b;
  356. break;
  357. default:
  358. break;
  359. }
  360. return result;
  361. }

main 函数

  1. #include <iostream>
  2. #include"Game24Points.h"
  3. using namespace std;
  4. int main()
  5. {
  6. int a,b,c,d;
  7. do
  8. {
  9. cin>>a>>b>>c>>d;
  10. if(!Game24Points(a,b,c,d))
  11. {
  12. cout<<"No Answer"<<endl;
  13. }
  14. } while (1);
  15. system("pause");
  16. return 0;
  17. }

24点游戏问题优化解:

  1. /******************************************************************************
  2. Copyright (C), 2001-2013, Huawei Tech. Co., Ltd.
  3. ******************************************************************************
  4. File Name :
  5. Version :
  6. Author :
  7. Created : 2013/03/12
  8. Last Modified :
  9. Description :
  10. Function List :
  11. History :
  12. 1.Date : 2013/03/12
  13. Author :
  14. Modification: Created file
  15. ******************************************************************************/
  16. #include"OJ.h"
  17. #include<string>
  18. #include<vector>
  19. #include<stack>
  20. #include <iostream>
  21. #include<algorithm>
  22. #include<sstream>
  23. using namespace std;
  24. void CalOpSymbolSet(char(*symbol_set)[3]);
  25. static int IndexOfSymbol(char sym);
  26. static char CompareSymbolPriority(char sym1, char sym2);//比较符号优先级
  27. static void PopSymbolToPostfixExpression(stack<char> &symbol_stack, vector<string> &postfix_expression);
  28. static vector<string> InfixToPostfixExpression(const string &infix_expression);
  29. static string int_to_string(const int n);//int to string
  30. static double CalSubExpressionResult(double a, double b, char symbol);
  31. static double CalPostfixExpressionValue(const vector<string>& postfix_expression);
  32. //运算符的优先关系比对表
  33. static char symbol_priority[4][4] = {
  34. /* 符号优先级表 /* '+' '-' '*' '/' */
  35. /* '+' */{ '=', '=', '<', '<',},
  36. /* '-' */{ '=', '=', '<', '<',},
  37. /* '*' */{ '>', '>', '=', '=',},
  38. /* '/' */{ '>', '>', '=', '=' } };
  39. bool Game24Points(int a, int b, int c, int d)
  40. {
  41. int num_array[4] = { a,b,c,d };
  42. char symbol_set[64][3];//运算符号组合
  43. string infix_expression;//中缀表达式
  44. vector<string> postfix_expression;//后缀表达式
  45. double expression_result = 0.0;
  46. //1. 计算符号组合
  47. int count = 0;
  48. CalOpSymbolSet(symbol_set);
  49. //2.计算输入数字的字典序排列
  50. sort(num_array, num_array + 4);
  51. do
  52. {
  53. for (int i = 0; i < 64; i++)
  54. for (int j = 0; j < 7; j++)
  55. {
  56. switch (j)
  57. {
  58. case 0://无括号类型
  59. infix_expression = int_to_string(num_array[0]) + symbol_set[i][0] + int_to_string(num_array[1]) + symbol_set[i][1] + int_to_string(num_array[2])
  60. + symbol_set[i][2] + int_to_string(num_array[3]);
  61. break;
  62. case 1://(a+b)*c-d类型
  63. infix_expression = "(" + int_to_string(num_array[0]) + symbol_set[i][0] + int_to_string(num_array[1]) + ")" + symbol_set[i][1] + int_to_string(num_array[2])
  64. + symbol_set[i][2] + int_to_string(num_array[3]);
  65. break;
  66. case 2://a+(b*c)-d类型
  67. infix_expression = int_to_string(num_array[0]) + symbol_set[i][0] + "(" + int_to_string(num_array[1]) + symbol_set[i][1] + int_to_string(num_array[2]) + ")"
  68. + symbol_set[i][2] + int_to_string(num_array[3]);
  69. break;
  70. case 3://a+b*(c-d)类型
  71. infix_expression = int_to_string(num_array[0]) + symbol_set[i][0] + int_to_string(num_array[1]) + symbol_set[i][1] + "(" + int_to_string(num_array[2])
  72. + symbol_set[i][2] + int_to_string(num_array[3]) + ")";
  73. break;
  74. case 4://(a+b*c)-d类型
  75. infix_expression = "(" + int_to_string(num_array[0]) + symbol_set[i][0] + int_to_string(num_array[1]) + symbol_set[i][1] + int_to_string(num_array[2])
  76. + ")" + symbol_set[i][2] + int_to_string(num_array[3]);
  77. break;
  78. case 5://a+(b*c-d)类型
  79. infix_expression = int_to_string(num_array[0]) + symbol_set[i][0] + "(" + int_to_string(num_array[1]) + symbol_set[i][1] + int_to_string(num_array[2])
  80. + symbol_set[i][2] + int_to_string(num_array[3]) + ")";
  81. break;
  82. case 6://(a+b)*(c-d)类型
  83. infix_expression = "(" + int_to_string(num_array[0]) + symbol_set[i][0] + int_to_string(num_array[1]) + ")" + symbol_set[i][1] + "(" + int_to_string(num_array[2])
  84. + symbol_set[i][2] + int_to_string(num_array[3]) + ")";
  85. break;
  86. default:
  87. break;
  88. }
  89. postfix_expression = InfixToPostfixExpression(infix_expression);
  90. expression_result=CalPostfixExpressionValue(postfix_expression)-24;
  91. if (expression_result<0.001&&expression_result>(-0.001))
  92. {
  93. cout<<infix_expression<<endl;
  94. return true;
  95. }
  96. }
  97. } while (next_permutation(num_array, num_array + 4));//求下一个字典序排列
  98. return false;
  99. }
  100. string int_to_string(const int n)
  101. {
  102. ostringstream oss;//创建一个流
  103. oss << n;//把值传递如流中
  104. return oss.str();//返回转换后的字符串
  105. }
  106. //1. 计算符号组合
  107. void CalOpSymbolSet(char(*symbol_set)[3])//计算运算符组合(‘+’、‘-’、‘*’、‘/')
  108. {
  109. char sym[4] = { '+','-','*','/' };
  110. for (int i = 0; i < 4; i++)
  111. for (int j = 0; j < 4;j++)
  112. for (int k = 0; k < 4; k++)
  113. {
  114. (*symbol_set)[0] = sym[i];
  115. (*symbol_set)[1] = sym[j];
  116. (*symbol_set)[2] = sym[k];
  117. ++symbol_set;
  118. }
  119. }
  120. //3. 中缀表达式变后缀表达式并计算值
  121. vector<string> InfixToPostfixExpression(const string &infix_expression)
  122. {
  123. size_t i = 0;
  124. vector<string> postfix_expression;
  125. stack<char> symbol_stack;//符号栈
  126. char ch = infix_expression[i++];
  127. while (i <= infix_expression.size())
  128. {
  129. if (isdigit(ch))//1.遇到数字,直接输出
  130. {
  131. string digit;
  132. while (isdigit(ch))
  133. {
  134. digit.push_back(ch);
  135. ch = infix_expression[i++];
  136. }
  137. postfix_expression.push_back(digit);
  138. }
  139. else
  140. {
  141. if (symbol_stack.empty()||ch=='('||symbol_stack.top()=='(')//2.遇到符号:栈为空或符号为'('或栈顶为‘(',符号直接入栈
  142. {
  143. symbol_stack.push(ch);
  144. ch = infix_expression[i++];
  145. }
  146. else if (ch == ')')//3. 遇到右括号,弹出所有栈中符号直到左括号并输出(左括号不输出)
  147. {
  148. while (symbol_stack.top()!='(')
  149. {
  150. PopSymbolToPostfixExpression(symbol_stack, postfix_expression);
  151. }
  152. symbol_stack.pop();//弹出左括号,不输出
  153. ch = infix_expression[i++];
  154. }
  155. else
  156. {
  157. while (!symbol_stack.empty())
  158. {
  159. char sym_priority = CompareSymbolPriority(symbol_stack.top(), ch);
  160. if (sym_priority == '>' || sym_priority == '=')//4.弹出优先级大于等于ch的所有符号
  161. PopSymbolToPostfixExpression(symbol_stack, postfix_expression);
  162. else
  163. break;
  164. }
  165. symbol_stack.push(ch);//压入符号
  166. ch = infix_expression[i++];
  167. }
  168. }
  169. }
  170. while (!symbol_stack.empty())//弹出栈中剩余符号
  171. {
  172. PopSymbolToPostfixExpression(symbol_stack, postfix_expression);
  173. }
  174. return postfix_expression;
  175. }
  176. //弹出栈中符号并输出到后缀表达式
  177. void PopSymbolToPostfixExpression(stack<char> &symbol_stack, vector<string> &postfix_expression)
  178. {
  179. if (symbol_stack.empty())
  180. return;
  181. string a(1, '#');
  182. a[0] = symbol_stack.top();
  183. symbol_stack.pop();
  184. postfix_expression.push_back(a);
  185. }
  186. //3. 计算后缀表达式的值
  187. double CalPostfixExpressionValue(const vector<string>& postfix_expression)
  188. {
  189. stack<double> exp_data;
  190. for (size_t i=0;i<postfix_expression.size();i++)
  191. {
  192. if(isdigit(postfix_expression[i][0]))
  193. {
  194. double data = atof(postfix_expression[i].c_str());
  195. exp_data.push(data);
  196. }
  197. else
  198. {
  199. double num1,num2;
  200. num2 = exp_data.top();
  201. exp_data.pop();
  202. num1 = exp_data.top();
  203. exp_data.pop();
  204. double temp_result= CalSubExpressionResult(num1,num2,postfix_expression[i][0]);
  205. exp_data.push(temp_result);
  206. }
  207. }
  208. return exp_data.top();
  209. }
  210. char CompareSymbolPriority(char sym1, char sym2)//中缀变后缀比较符号优先级
  211. {
  212. int index1 = IndexOfSymbol(sym1);
  213. int index2 = IndexOfSymbol(sym2);
  214. return symbol_priority[index1][index2];
  215. }
  216. int IndexOfSymbol(char sym)//符号优先级索引
  217. {
  218. int index;
  219. switch (sym)
  220. {
  221. case '+':
  222. index = 0;
  223. break;
  224. case '-':
  225. index = 1;
  226. break;
  227. case '*':
  228. index = 2;
  229. break;
  230. case '/':
  231. index = 3;
  232. break;
  233. case '(':
  234. index = 4;
  235. break;
  236. case ')':
  237. index = 5;
  238. break;
  239. case '=':
  240. index = 6;
  241. break;
  242. default:
  243. break;
  244. }
  245. return index;
  246. }
  247. double CalSubExpressionResult(double a, double b, char symbol)
  248. {
  249. double result = 0.0;
  250. switch (symbol)
  251. {
  252. case '+':
  253. result = a + b;
  254. break;
  255. case '-':
  256. result = a - b;
  257. break;
  258. case '*':
  259. result = a*b;
  260. break;
  261. case '/':
  262. result = a / b;
  263. break;
  264. default:
  265. break;
  266. }
  267. return result;
  268. }

参考:
计算表达式值:http://www.cnblogs.com/heyonggang/p/3359565.html
中缀表达式、后缀表达式:
1. http://www.cnblogs.com/heyonggang/p/3359565.html
2. http://www.cnblogs.com/mygmh/archive/2012/10/06/2713362.html
3. http://blog.csdn.net/girlkoo/article/details/17435717
4. http://www.acmerblog.com/infix-to-postfix-6072.html
24点游戏,集合解法http://www.cnblogs.com/Quincy/archive/2012/03/26/2418546.html

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注