题意:
给出一个表达式字符串,判断序列中哪些括号是可以去掉的,只可以改变符号。输出括号最少的序列
思路:
用一个vis数组记录那个字符可以不输出,那个字符要输出。初始时,vis[i] = 0,当不可以改变是标记为-1,当可以去掉是标记为1。
首先找到所有括号对,记录他们的始末坐标和长度,按照区间长度从小到大排序。先处理小区间,再处理大区间。
#include <cstdio>
#include <stack>
#include <vector>
#include <cstring>
#include <algorithm>
#define fi first
#define se second
#define pii pair<int,int>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
const int maxn = 1000+5;
char str[maxn];
int vis[maxn];
// 每对括号
struct Bracket{
int l,r;
int d; // 括号长度
bool operator < (const Bracket& rhs) const{
return d < rhs.d||(d == rhs.d&&l < rhs.l);
}
}B[maxn];
int judge(int x){
if(str[x] == '+') return 1;
else if(str[x] == '-') return 2;
else if(str[x] == '*') return 3;
else if(str[x] == '/') return 4;
return -1;
}
void solve(){
memset(vis, 0, sizeof(vis));
// 记录每一对括号的始末位置
stack<int> S;
int cnt = 0; // 括号对数
int len = strlen(str+1);
for(int i = 1; i <= len; ++i){
if(str[i] == '(') S.push(i);
else if(str[i] == ')'){
B[cnt].l = S.top(); S.pop();
B[cnt].r = i;
B[cnt].d = B[cnt].r - B[cnt].l;
++cnt;
}
}
sort(B, B+cnt); // 按照长度排序
for(int i = 0; i < cnt; ++i){
bool flag = true;
int L = B[i].l, R = B[i].r;
int left_op = judge(L - 1);
int right_op = judge(R + 1);
// 前面或后面有*/
if(left_op == 3||left_op == 4||right_op == 3||right_op == 4){
for(int j = L+1; j < R; ++j){
if(vis[j] == -1) continue;
if(str[j] == '+'||str[j] == '-'){ flag = false; break;}
}
// 不可改变
if(!flag){
for(int j = L; j <= R; ++j){
if(vis[j] == 0) vis[j] = -1;
}
}
}
// 前面没有符号或是+
if(flag&&(left_op == -1||left_op == 1)){
vis[L] = vis[R] = 1;
}
// 前面是-
if(flag&&left_op == 2){
vis[L] = vis[R] = 1;
for(int j = L+1; j < R; ++j){
if(vis[j] == -1) continue;
if(str[j] == '+') str[j] = '-';
else if(str[j] == '-') str[j] = '+';
}
}
// 乘号
if(flag&&left_op == 3){
vis[L] = vis[R] = 1;
}
// 除号
if(flag&&left_op == 4){
vis[L] = vis[R] = 1;
for(int j = L+1; j < R; ++j){
if(vis[j] == -1) continue;
if(str[j] == '*') str[j] = '/';
else if(str[j] == '/') str[j] = '*';
}
}
}
for(int i = 1; i <= len; ++i){
if(vis[i] != 1) printf("%c",str[i]);
}puts("");
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%s",str+1) == 1){
solve();
}
return 0;
}