fork(2) download
  1. #include<bits/stdc++.h>
  2. #define ll long long
  3. #define pb push_back
  4. using namespace std;
  5. int lv(char c){
  6. if(c=='+'||c=='-') return 1;
  7. else if(c=='*'||c=='/') return 2;
  8. else if(c=='(') return 0;
  9. }
  10. int Isoperator(string s){
  11. if(s=="*") return 3;
  12. if(s=="/") return 4;
  13. if(s=="+") return 1;
  14. if(s=="-") return 2;
  15. return 0;
  16. }
  17. string llToString(ll n){
  18. string res="";
  19. if(n==0){
  20. res="0";
  21. return res;
  22. }
  23. char s[4];
  24. int i=0,minus=0;
  25. if(n<0){
  26. minus=1;
  27. n=-n;
  28. res="-";
  29. }
  30. while(n){
  31. s[i]=n%10+'0';
  32. n/=10;
  33. i++;
  34. }
  35. for(int j=i-1;j>=0;j--){
  36. res+=(char)(s[j]);
  37. }
  38. return res;
  39. }
  40. ll StringToll(string s){
  41. ll res=0;
  42. for(int i=0;i<s.length();i++){
  43. res=res*10+s[i]-'0';
  44. }
  45. return res;
  46. }
  47. string dothePoland(string a,string b,int n){
  48. ll p1=StringToll(a),p2=StringToll(b);
  49. switch(n){
  50. case 1:return llToString(p1+p2);break;
  51. case 2:return llToString(p1-p2);break;
  52. case 3:return llToString(p1*p2);break;
  53. case 4:return llToString(p1/p2);break;
  54. }
  55. }
  56. void done(string s){
  57. int n=s.length();
  58. stack <char> st;
  59. vector <string> out;
  60. for(int i=0;i<n;i++){// dang ba lan
  61. if(s[i]>='0'&&s[i]<='9'){
  62. string t="";
  63. t+=(char)s[i];
  64. while(i<n-1&&s[i+1]<='9'&&s[i+1]>='0'){
  65. t+=(char)s[i+1];
  66. i++;
  67. }
  68. out.pb(t);
  69. }
  70. else if(s[i]=='(') st.push(s[i]);
  71. else if(s[i]!=')'){
  72. while(!st.empty()){
  73. if(lv(st.top())>=lv(s[i])){
  74. string t="";t+=(char)st.top();
  75. out.pb(t);
  76. st.pop();
  77. }
  78. else break;
  79. }
  80. st.push(s[i]);
  81. }
  82. else{
  83. while(st.top()!='('){
  84. string t="";t+=(char)st.top();
  85. out.pb(t);
  86. st.pop();
  87. }
  88. st.pop();
  89. }
  90. }
  91. while(!st.empty()){
  92. string t="";t+=(char)st.top();
  93. out.pb(t);
  94. st.pop();
  95. }
  96. for(int i=2;i<out.size();){//thuc hien tinh toan
  97. if(Isoperator(out[i])){
  98. out[i-2]=dothePoland(out[i-2],out[i-1],Isoperator(out[i]));
  99. out.erase(out.begin()+i-1,out.begin()+i+1);
  100. i--;
  101. }
  102. else i++;
  103. }
  104. cout<<out[0]<<endl;
  105. }
  106. int main(){
  107. ios_base::sync_with_stdio(false);
  108. int N;
  109. cin>>N;
  110. while(N--){
  111. string s;
  112. cin>>s;
  113. done(s);
  114. }
  115. }
Success #stdin #stdout 0s 4564KB
stdin
4

6*3+2-(6-4/2)

100+99*22

6*((4*3)+5)

1-2
stdout
16
2278
102
-1