fork download
  1. #include<iostream>
  2. #include<stack>
  3. using namespace std;
  4. long long int getValueAfter(char str[],long long int index,long long int &i){
  5. long long int val = 0;
  6. while(str[index] && str[index]>='0' && str[index]<='9'){
  7. val = val*10 + str[index] - '0';
  8. index++;
  9. }
  10. i = index - 1;
  11. return (val?val:1);
  12. }
  13. long long int prevValue(stack<long long int> &s){
  14. long long int val = 0;
  15. while(!s.empty()){
  16. val += s.top();
  17. s.pop();
  18. }
  19. return val;
  20. }
  21. int main(){
  22. long long int test_case,c;
  23. cin>>test_case;
  24. cin>>ws;
  25. while(test_case--){
  26. c=0;
  27. char str[1000001];
  28. cin>>str;
  29. long long int i,topValue,vAfter,parenthesis=0;
  30. stack<long long int> s;
  31. long long int res = 0;
  32. bool flag = 1; // 1 means current parenthesis so add with top value
  33. s.push(0);
  34. stack<char>CheakP;
  35. int cflag=1;
  36. for(i=0;str[i]!='\0';i++){
  37. if(str[i]=='('){
  38. s.push(0);
  39.  
  40. }
  41. else if(str[i]==')'){
  42. vAfter = getValueAfter(str,i+1,i); // update i also
  43. topValue = s.top();
  44. s.pop();
  45. long long int temp = 0;
  46. if(!s.empty()){
  47. temp = s.top();
  48. s.pop();
  49.  
  50. }
  51.  
  52. s.push(temp + topValue*vAfter);
  53. }
  54. else if(str[i]=='C'){
  55. vAfter = getValueAfter(str,i+1,i); // update i also
  56. topValue = s.top();
  57. s.pop();
  58. s.push(topValue + vAfter);
  59. }
  60. if(str[i]=='(')
  61. CheakP.push(str[i]);
  62. if(str[i]==')'){
  63. if(CheakP.empty())
  64. cflag=0;
  65. else if(CheakP.top()!='(')
  66. cflag=0;
  67. else
  68. CheakP.pop();
  69. }
  70. if(!cflag)
  71. break;
  72. }
  73. res = prevValue(s);
  74.  
  75. if(!cflag||CheakP.empty())
  76. cout<<"INVALID"<<endl;
  77. else
  78. cout<<res<<endl;
  79. }
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0s 4336KB
stdin
3

(COH)2(C2H)3

(C2)2(C2)C))

C3(C)4
stdout
8
INVALID
7