POJ-1400(删除冗余括号)
来源:互联网 发布:阿里旺旺网络连接失败 编辑:程序博客网 时间:2024/05/20 23:08
题目:http://poj.org/problem?id=1400
一开始在判断括号内是否全是乘或除时忘了括号内还有括号的情况,WA了两次之后找到了数据,对比答案之后才发现这个问题……删括号规则:
(1)括号前是除号,不能删
(2)括号前是乘号或减号,如果括号内全是乘除法或者被括号括起来的运算
(3)括号前是加法,如果括号后面是加法、括号后面是减法、括号内全是乘除法或者被括号括起来的运算
#include <string>#include <iostream>using namespace std;inline bool isOperator(char c){ return c == '+' || c == '-' || c == '*' || c == '/';}bool allMulOrDiv(const string& exp){ for(int i = 0, len = exp.size(); i < len; ++i){ if(exp[i] == '('){ int cnt = 1; for(++i; true; ++i){ if(exp[i] == '(') ++cnt; else if(exp[i] == ')'){ --cnt; if(!cnt) break; } } ++i; } if(exp[i] == '+' || exp[i] == '-') return false; } return true;}int findMatchedLeft(const string& exp, int r){ int countOfRight = 1; for(--r; r >= 0; --r){ if(exp[r] == ')') ++countOfRight; else if(exp[r] == '('){ --countOfRight; if(!countOfRight) break; } } return r;}string& simplify(string& exp){ int left, right = 0; char head, tail, can; while((right = exp.find(')', right)) != string::npos){ left = findMatchedLeft(exp, right); //get info if(left && isOperator(exp[left-1])) head = exp[left-1]; else head = '+'; if(right+1 < exp.size() && isOperator(exp[right+1])) tail = exp[right+1]; else tail = '+'; //analyze if(right - left == 2) can = 1; else if(head == '/') can = 0; else if(head == '*' || head == '-') can = allMulOrDiv(exp.substr(left+1, right-left-1)); else can = tail == '+' || tail == '-' || allMulOrDiv(exp.substr(left+1, right-left-1)); //process if(can){ exp.erase(left, 1).erase(right - 1, 1); --right; } else ++right; } return exp;}int main(){ ios::sync_with_stdio(false); int test; cin >> test; while(cin.get() != '\n') cin.get(); string exp; while(test--){ getline(cin, exp); cout << simplify(exp) << "\n"; } return 0;}
0 0
- POJ-1400(删除冗余括号)
- 删除冗余文件
- 删除冗余约束
- Linux删除冗余垃圾文件
- Oracle删除冗余垃圾文件
- sql删除冗余数据
- mysql删除冗余数据
- 如何删除数据库中的冗余数据(翻译)
- 如何删除数据库中的冗余数据(翻译)
- 如何删除数据库中的冗余数据(翻译)
- Quartz定时任务删除冗余操作日志(二)
- POJ-3991(左括号右括号调整)
- SQLPLUS中删除冗余信息
- Python删除冗余文件技巧
- 删除数组中冗余元素
- 删除数据库中冗余信息
- poj 2955 区间dp(括号匹配)
- POJ 2955 (dp括号匹配)
- Uva1626 线性DP
- 自用收藏的链接
- 给定一整型数组,若数组中某个下标值大的元素值小于某个下标值比它小的元素值,称这是一个反序
- LeetCode 1 Reverse Words in a String
- 2大类型的设备驱动程序(2 main types of device driver)
- POJ-1400(删除冗余括号)
- 迷茫
- UVA307
- 实现算法2.4的程序
- Airport(凸包加点与直线的距离)
- 在VS2010下建立cocos2dx项目
- Leetcode--Reorder List
- 二分图 zoj 1137 poj 1325 poj1422 hdu2063 hdu1498
- 工作流任务的超时计算