Help required for ONP

,

#include <stdio.h>
#include <string.h>

void del(char * stk, int *top, char * res, int *rest);

int main()
{
int t, i=0, j=0, top=-1, rest=-1, l=0;
char expr[400]={'\0'};
char stk[50]={'\0'}, res[400]={'\0'};

scanf("%d", &t);

for (i=0;i<t;i++) {
    scanf("%s", expr);
    l=strlen(expr);
    rest = -1;
    top=-1;
    for (j=0;j<l;j++) {
        switch(expr[j])
        {
            case '(': stk[++top] = '(';
                    break;
            case '+':
            case '-':
            case '*':
            case '/':
            case '^':
                    stk[++top] = expr[j];
                    break;
            case ')':
                    del(stk, &top, res, &rest);
                    break;
            default: res[++rest] = expr[j];
        }
    }
    printf("%s\n", res);
}
return 0;
}

void del(char * stk, int *top, char * res, int *rest) {
do {
        res[++(*rest)] = stk[*(top)];
        stk[(*top)--]='\0';
} while(stk[*top]!='(' && *top>=0);
      (*top)--;
}

The compiler which it runs on (code::blocks12.11), it gives correct answer. On codechef it says that it gives the wrong answer.

You are not initializing the stack (to null in your case) for each test case. So whenever the previous input has a larger expression than current input, your code will give wrong answer. E.g. try following case:

3

((a+t)*((b+(a+c))^(c+d)))

((a+b)*(z+x))

(a+(b*c))

Your code gives WA for this.
Initialize the stack to null for every test case.

1 Like