#include<bits/stdc++.h> using namespace std; #define SPEED ios::sync_with_stdio(false);cin.tie(NULL); #define ll long long int main() { SPEED; ll test; cin>>test; map<char,int> m; m.insert(pair<char,int>('-',1)); m.insert(pair<char,int>('+',1)); m.insert(pair<char,int>('*',2)); m.insert(pair<char,int>('/',2)); m.insert(pair<char,int>('^',3)); while(test--) { ll n; cin>>n; string s; cin>>s; ll i=0; stack<char> A; string res=""; for (ll i=0;i<s.size();i++) { if(s[i]>=65 && s[i]<=90 || s[i]>=97 && s[i]<=132) { res=res+s[i]; } else if(s[i]=='(') { A.push(s[i]); } else if(s[i]==')') { while(A.top()!='(' && !A.empty()) { res=res+A.top(); A.pop(); } A.pop(); } else { if(A.empty()) A.push(s[i]); else if(A.top()=='(') A.push(s[i]); else if(m[A.top()]<=m[s[i]]) A.push(s[i]); else{ while(A.top()!='(' && !A.empty() && m[A.top()]>m[s[i]]) { res=res+A.top(); A.pop(); } A.push(s[i]); } } } while(!A.empty()) { res=res+A.top(); A.pop(); } cout<<res<<"\n"; } return 0; } indent preformatted text by 4 spaces
You have to flip this.
while(!A.empty() && A.top()!='(')
Because if A
is in fact empty, you’ll be trying to access A.top()
which results in the RE.
3 Likes
while(A.top()!=’(’ && !A.empty())
If your stack is empty and above checks the first condition which is “A.top()!=’(’” u get RE as it not going to check the next condition.
Basically, we know both the condition should be true with the && as satisfy our need, but in what order these conditions are executed.
Its first condition will execute first and then the second condition.
u should use —> while ( !A.empty() && A.top != ‘(’ )