[关闭]
@Scarlet 2018-11-17T09:28:10.000000Z 字数 1669 阅读 1783

调度场算法

表达式计算


一个看了就会写的图例

调度场算法

伪代码

对于一个仅含四则运算的表达式,我们可以通过这样操作把它变成后缀表达式

对于一个后缀表达式,我们可以这样计算它

注意到前算法的输出队列和后算法的入栈顺序相同,那么让两个算法同时进行就是计算表达式了。

轻松简单的实现

  1. /*
  2. Author: Scarlet
  3. */
  4. #include <stdio.h>
  5. #include <ctype.h>
  6. #include <string.h>
  7. char ops[4] = "+-*/", S[1000];
  8. int st[1000], tp, TP;
  9. double ST[1000];
  10. int getnxt(int *x, int *i)
  11. {
  12. char ch = S[*i];
  13. int _[233], __[233];
  14. _['('] = 2, _[')'] = 3, _['+'] = 4, _['-'] = 4, _['*'] = 4, _['/'] = 4;
  15. __['('] = 0, __[')'] = 0, __['+'] = 0, __['-'] = 1, __['*'] = 2, __['/'] = 3;
  16. if (isdigit(ch))
  17. {
  18. for (*x = 0; isdigit(S[*i]); ++*i)
  19. *x = *x * 10 + S[*i] - 48;
  20. return 1;
  21. }
  22. else
  23. return *x = __[ch], ++*i, _[ch];
  24. }
  25. void prt(int op,int x)//后缀表达式转值
  26. {
  27. if(op==0)
  28. {
  29. printf("%d ", x);
  30. ST[TP++] = (double)x;
  31. }
  32. else
  33. {
  34. printf("%c ", ops[x]);
  35. double Y = ST[TP - 1], X = ST[TP - 2];TP--;
  36. if (x == 0)
  37. ST[TP - 1] = X + Y;
  38. else if(x==1)
  39. ST[TP - 1] = X - Y;
  40. else if(x==2)
  41. ST[TP - 1] = X * Y;
  42. else
  43. ST[TP - 1] = X / Y;
  44. }
  45. }
  46. int main()
  47. {
  48. freopen("w.in", "r", stdin);
  49. scanf("%s", S);
  50. int L = strlen(S);
  51. for (int i = 0; i < L;)
  52. {
  53. int x, op = getnxt(&x, &i);
  54. if (op == 1)
  55. prt(0, x);
  56. else if (op == 4)
  57. {
  58. for (; tp && st[tp - 1] / 2 >= x / 2;)
  59. prt(1, st[--tp]);
  60. st[tp++] = x;
  61. }
  62. else if (op == 2)
  63. st[tp++] = -2;
  64. else
  65. for (tp--; tp && st[tp] != -2;)
  66. prt(1, st[tp--]);
  67. }
  68. for (; tp;)
  69. prt(1, st[--tp]);
  70. printf("\n%lf\n", ST[0]);
  71. return 0;
  72. }

小结

这也太强了吧QAQ

惊了,怕是大学里学的第一个算法= =

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