CCF 201903-2 二十四点

逃离我推掉我的手 2023-07-17 06:40 122阅读 0赞

CCF 201903-2 二十四点

  1. //
  2. // Created by asimov on 2020/3/20.
  3. //CCF
  4. //201903-2 二十四点
  5. //
  6. #ifndef CSP_24P_H
  7. #define CSP_24P_H
  8. #endif //CSP_24P_H
  9. #include <bits/stdc++.h>
  10. using namespace std;
  11. stack<int> numStack;//操作数栈
  12. stack<char> operationStack;//操作符栈
  13. string str;
  14. int p() {
  15. int n, front, back, i, j;
  16. cin >> n;
  17. getchar(); //读取换行符,易漏!!!
  18. for (i = 0; i < n; i++) {
  19. while (!numStack.empty()) numStack.pop();//清空栈
  20. while (!operationStack.empty()) operationStack.pop();
  21. cin >> str;//读取字符串
  22. //cout<<str.length()<<endl;
  23. for (j = 0; j < str.length(); j++) {
  24. if (str[j] >= '0' && str[j] <= '9')//若为数字,压入nd栈中
  25. {
  26. numStack.push(str[j] - '0');
  27. } else if (str[j] == '+') //若为'+',压入op栈中
  28. {
  29. operationStack.push('+');
  30. } else if (str[j] == '-')//转化为"+"计算(即将正数存储为负数,而op栈中就可以存放'+'了)
  31. {
  32. numStack.push((str[j + 1] - '0') * (-1));
  33. operationStack.push('+');
  34. j++;
  35. } else if (str[j] == 'x')//先乘除法,与下一个未压入栈的数字计算,将计算结果压入数栈;
  36. {
  37. front = numStack.top();
  38. numStack.pop();
  39. back = str[j + 1] - '0';
  40. numStack.push(front * back);
  41. j++;//已经使用了后一位操作数 因此跳过
  42. } else if (str[j] == '/') {
  43. front = numStack.top();
  44. numStack.pop();
  45. back = str[j + 1] - '0';
  46. numStack.push(front / back);
  47. j++;
  48. }
  49. }
  50. while (!operationStack.empty())//此时只剩下'+'未计算了
  51. {
  52. // 取两个操作数
  53. front = numStack.top();
  54. numStack.pop();
  55. back = numStack.top();
  56. numStack.pop();
  57. operationStack.pop();
  58. numStack.push(front + back);
  59. }
  60. // cout<<numStack.top()<<endl;
  61. if (numStack.top() == 24)//取出栈中数字,看是否=24
  62. cout << "Yes" << endl;
  63. else
  64. cout << "No" << endl;
  65. }
  66. return 0;
  67. }

/*
10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5
*/

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,122人围观)

还没有评论,来说两句吧...

相关阅读

    相关 游戏Python实现

    二十四点游戏是一种数学益智游戏,通过组合四个数字和四种基本运算符(加、减、乘、除),使得计算结果等于24。在本文中,我们将使用Python语言实现这个游戏。 一、游戏规则

    相关 CCF 击窗口

    一.问题描述 在某图形操作系统中,有 N 个窗口,每个窗口都是一个两边与坐标轴分别平行的矩形区域。窗口的边界上的点也属于该窗口。窗口之间有层次的区别,在多于一个窗口重叠的

    相关 CCF计数

    一.问题描述 给定n个整数表示一个商店连续n天的销售量。如果某天之前销售量在增长,而后一天销售量减少,则称这一天为折点,反过来如果之前销售量减少而后一天销售量增长,也称这