Thursday, April 5, 2018

UVa problem solution 727 - Equation

problem link:

Discuss: in this problem you may first trouble with taking input.it's quite okay it's a terrific one before but it's not like that. you can take input as string and if the first character of string is null character just break the loop.and obviously give a null end of your main string. and other simply need to convert it infix to post fix. if you know stack then it just  a implementation problem for you.

try your self, before see the code




#include<bits/stdc++.h>
using namespace std;
char postfix[2500];
int p=0;
bool IsOprator(char ch)
{
    if(ch=='+'||ch=='-'||ch=='/'||ch=='*')
        return true;
    return false;
}
bool precedence(char x,char y)
{
    if(x=='*'||x=='/')
        return true;
    else if(y=='*'||y=='/')
        return false;
    return true;
}
char *Make_Postfix(char str[],int n)
{
    int i;
    stack<char>stk;
    stk.push('(');
    for(i=0; i<n; i++)
    {
        if(IsOprator(str[i]))
        {
            while(precedence(stk.top(),str[i])&&IsOprator(stk.top())&&!stk.empty())
            {
                postfix[p++]=stk.top();
                stk.pop();
            }
            stk.push(str[i]);
        }
        else if(str[i]==')')
        {
            while(!stk.empty()&&stk.top()!='(')
            {
                postfix[p++]=stk.top();
                stk.pop();
            }
            stk.pop();
        }
        else if(str[i]=='(')
            stk.push(str[i]);
        else
        {
            postfix[p++]=str[i];
        }
    }
    while(!stk.empty()&&stk.top()!='(')
    {
        postfix[p++]=stk.top();
        stk.pop();
    }
    postfix[p++]='\0';
    return postfix;
}
int main()
{

    int t;
    cin >>t;
    while(t--)
    {

        char str[2000],ch;
        int n,i=0,j;


        scanf("\n");
        while(1)
        {
            string s;
            getline(cin,s);
            if(s[0]=='\0')
                break;
            str[i++]=s[0];
        }
        str[i++]='\0';
        n=strlen(str);
        cout <<Make_Postfix(str,n)<<endl;
        postfix[0]='\0';
        p=0;
        if(t>=1)
            cout <<endl;
    }

    return 0;
}

No comments:

Post a Comment