Uva1662括号-字符串

本文介绍了一种用于优化表达式字符串中括号的算法,通过判断哪些括号对可以被安全地去除,从而简化数学表达式的解析过程。算法采用深度优先搜索策略,结合优先级判断,确保表达式的正确性和简洁性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

给出一个表达式字符串,判断序列中哪些括号是可以去掉的,只可以改变符号。输出括号最少的序列

思路:

用一个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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值