My solution for Transform the expression gives Wrong answer.

Problem Link - http://www.codechef.com/problems/ONP

My program runs for all inputs I tried, but still gives wrong answer.

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<ctype.h>
using namespace std;

int transform(char a[401])
{
    int n = strlen(a),i,j,k,l,m,f;
    for(int o=1;;o++)
    {
        f=0;
        for(i=n-1;i>=0;i--)
        {
            if(a*=='(')
            {
                a*=-1;
                f=1;
                break;
            }



        }
        if (f==0)
        {
            break;
        }
        for(j=i+1;;j++)
        {
            if(isalpha(a[j])==0&&a[j]!=-1)
                break;
        }
        for(k=j;;k++)
        {
            if(isalpha(a[k])!=0)
            {
                break;
            }

        }
        while((a[k]==-1)||(isalpha(a[k])!=0)||(a[k]=='(')||(a[k]==')'))
        {
            k--;
        }
        for(l=k;;l++)
        {
            if(a[l]==')')
            {



                a[l]=a[k];
                a[k]=-1;
                break;
            }
        }

    }
    for(m=0;m<n;m++)
    {
        if((isalpha(a[m])!=0)||a[m]=='+'||a[m]=='-'||a[m]=='*'||a[m]=='/'||a[m]=='^')
        {
            cout<<a[m];
        }
    }
    return 0;
}

int main()
{
    char a[101][401];
    int times,q;
    cin>>times;
    for(q=1;q<=times;q++)
    {
    gets(a[q]);
    transform(a[q]);
    }
    return 0;

}

you are getting wrong answers for these type of test cases ((e+((a+b)+(c+d)))+(f+((e+d)+(g+h)))) correct answer for above test case is eab+cd+++fed+gh++++ but your answer is eabcd++++fed+gh++++ try to debug this test case you may get correct answer and don’t forget to print new line that is ’
’ after every test case
. i hope this test case will be helpful to you.
and a small hint for this problem from my side is

  • traverse the string when ever you encounter any operator push into stack
  • else if you encounter closed bracket pop the operator present in the stack
  • else other than brackets or operator that is any character just print that character
  • if you want to look at the code with the above algorithm you can look at this

Thank you, Happy coding :slight_smile:

1 Like

Thanks… I guess I need to learn more before trying out such problems… I have no idea what a stack is.

it’s ok you can just google it what stack is… :slight_smile: