reverse polish notation in c++

Jun 27, 2014 at 7:04pm
Question-->http://www.spoj.com/problems/ONP/
I m not able to find the problem in my solution . I m new to C++.My solution is working fine for the test cases i have tried. I m not able to find the bug.Plz help.It is giving wrong answer on both spoj and codechef
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<iostream>
#include<stack>
#include<string>
#include<stdio.h>
using namespace std;
int main()
{   int t,trap;
    cin>>t;
    trap=getchar();
    while(t--)
    {
    stack<char> S;
    string s1,s2;
    string::iterator it,jt;
    getline(cin,s1);
    s1.push_back(')');
    S.push('(');
    it=s1.begin();
    while(!S.empty())
    {
        if(*it=='('||*it=='+'||*it=='-'||*it=='*'||*it=='/'||*it=='^')
        {
            S.push(*it);
            it++;
        }
        else if(*it==')')
        {
            while(S.top()!='(')
            {
                s2.push_back(S.top());
                S.pop();
            }
            S.pop();
            it++;
        }
        else if(*it>='a'&&(*it)<='z')
        {
            s2.push_back(*it);
            it++;
        }

    }

    for(jt=s2.begin();jt<=s2.end();jt++)
    {
        cout<<*jt;
    }
    cout<<"\n";
    }
    return 0;
}
Last edited on Jun 27, 2014 at 7:05pm
Jun 27, 2014 at 9:00pm
You're giving all operators the same precedence, so your code transforms 1 + 2 * 3 into 1 2 + 3 *, rather than 1 2 3 * +.
Jun 28, 2014 at 3:44am
yes you are right.But i did this because in question it is mentioned that
forms like 1+2*3 will not be given as input instead (1+(2*3) ) will be given as input a/c to me we don't have to worry about the precendece order.It is bit ambguios because all the test cases they provided all operands are well within their bracket and also they wrote no forms of the form like(a*b*c) will be given .But on the other side they mention the precedence order of all the operators
Jun 28, 2014 at 4:18am
What it says is that the input will not contain infix expressions that could be correctly transformed to more than one postfix expression, such as a*b*c which has two postfix forms: a b c * * and a b * c *. 1 + 2 * 3 has only one equivalent postfix expression.
Topic archived. No new replies allowed.