zoj1423(Your)((Term)((Project))) (栈——基础练习)

来源:互联网 发布:网络美术培训 编辑:程序博客网 时间:2024/05/18 22:39

题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=423


说明:虽然这题不难,但是WA了几次,并且看了几个别人的代码,发现他们没有和我思路一样的。于是只能苦逼的想哪错了,后来发现a-(c-c-c+b)+((a+c)-(b-c))  这项数据会导致我的代码错误(括号没匹配上),改了下,终于AC了


思路:用俩个栈来实现。括号前面如果有-号,并且这个括号内有运算符号,则这个括号不能去掉,如-(a+b)


#include<stdio.h>#include<string.h>#include<stack>using namespace std;int main(){    int n;    char s[330];    stack<char> p,b;//b用于辅助    while(scanf("%d%*c",&n)!=EOF){        while(n--){            gets(s);            while(!p.empty())//清空俩个栈                p.pop();            while(!b.empty())                b.pop();            int len_s=strlen(s);            for(int i=0;i<len_s;i++){                if(s[i]==' ') continue;                if(s[i]!=')'){                    p.push(s[i]);                }else{                    int jian=0,flag=0,tot=0;//'('前一个元素是否是减号,'('')'之间是否有符号                    while(!p.empty()){                        char ch=p.top();                        p.pop();                        b.push(ch);                        if(ch!='('){                            if(ch=='+'||ch=='-')                                flag=1;                            if(ch==')') tot++;//tot的作用是使括号正确匹配,如((a+b)-(c+d))最后一个右括号应该和第一个左括号匹配                        }else{                            if(tot!=0) {tot--;continue;}                            else{//匹配成功                                if(!p.empty() &&p.top()=='-')                                    jian=1;                                break;                            }                        }                    }                    if(jian && flag){//这个括号不能删除                        while(!b.empty()){//将b栈全部压入p栈                            p.push(b.top());                            b.pop();                        }                        p.push(')');                    }else{                        b.pop(); //删除'(' ,右括号入栈                        while(!b.empty()){                            p.push(b.top());                            b.pop();                        }                    }                }            }            while(!p.empty()){//下面俩个while循环将p内容导入b,最后输出b                b.push(p.top());                p.pop();            }            while(!b.empty()){                printf("%c",b.top());                b.pop();            }            printf("\n");        }    }    return 0;}


0 0
原创粉丝点击