hoj12008 Parenthesis
来源:互联网 发布:淘宝如何批量发货 编辑:程序博客网 时间:2024/05/01 21:54
呵呵 。。。
这道题是2011年暑假培训时,跑出去打工回来后做的第一道题,纠结了许久,不过还是做出来了,
这道题目用的枚举的算法。题目式子中运算符只有加、乘、括号,所以括号两端可能出现的运算符的情况只有(3*3)种(不包括括号某一端为空的情况),如果为下面4种情况的话:
(1)a+(b+c)+a
(2) a+((b+c)+d)+a
(3) a+(a+(b+c))+a
(4) a+((b+c))+a
此时可以去掉该括号,其它情况(不包括括号某一端为空的情况)括号内内容都可以看做一个因子,如果括号内全为乘法,则括号亦可去掉。注意下面几种情况。
(1)a+((a+b)c+d)a+a
代码如下:
#include<iostream>#include<string>using namespace std;int main(){int i,j,k;char exp[1010], e[1010];int stack[510], flag[1010], top;while(scanf("%s", exp) != EOF){int length = strlen(exp);top = -1;for(i=0; i<length; i++){memset(flag, 0, sizeof(flag));for(j=0; j<length; j++)e[j] = exp[j];e[j] = '\0';if(e[i] == '('){stack[++top] = i;}else if(e[i] == ')'){int l, r;l = stack[top--];r = i;if((l == 0 || e[l-1] == '+' || e[l-1] == '(') && (r+1 == length || e[r+1] == '+' || e[r+1] == ')'))flag[r] = flag[l] = 1;else{bool isPri = true;int t = -1;for(j=l+1; j<r; j++)if(e[j] == '+' && t == -1)isPri = false;else if(e[j] == '(')t++;else if(e[j] == ')')t--;if(isPri == true){flag[r] = flag[l] = 1;}}}int len = 0;for(j=0; j<length; j++)if(flag[j] == 0){exp[len ++] = e[j];}else i--;exp[len] = '\0';length = len;}for(i=0; i<length; i++)cout<<exp[i];cout<<endl;}return 0;}
- hoj12008 Parenthesis
- Parenthesis
- Parenthesis
- Parenthesis
- unbalanced parenthesis
- Generate parenthesis
- csu Parenthesis
- Parenthesis CSU
- 【leetcode】 generate parenthesis !!
- sre_constants.error: unbalanced parenthesis
- TOJ 3407 Parenthesis
- Leetcode: Generate Parenthesis
- [Leetcode] Generate Parenthesis
- Longest Valid Parenthesis
- leetcode Generate Parenthesis
- leetcode Generate Parenthesis
- LeetCode - Valid Parenthesis
- LeetCode:Generating Parenthesis
- 好博客哦
- 原码反码补码加减运算
- 获取文件扩展名的通用方法
- perl+cgi学习
- 云存储:下一个互联网金矿?
- hoj12008 Parenthesis
- 优秀领导者的六种领导方式
- How to Improve Query Performance - A Checklist
- win32中使用MFC类库
- 【SEO系列学习专题】——000 序:为什么要学SEO,怎么学?
- #ifndef
- PB DataWindow 技巧大全
- java 多线程 线程池 工作队列
- 操作系统简介