UVa 817 数字表达式 (According to Bartjens)

博客介绍了在UVa 817题中解决数字表达式计算的问题,指出由于仅涉及加减乘除,不需转换为后缀表达式。文章强调2000这个数字在没有运算符情况下也是不可能的。该问题通过深度优先搜索(DFS)暴力求解,代码简洁,无剪枝需求。

题目:略

这一题做了两遍才做出来

有一些麻烦的点需要注意

1: 数字表达式的计算,这里由于只涉及到 ±* 因此其实没必要用中缀表达式转后缀表达式利用栈来计算,处理起来并不方便
2: 2000= 由于没有插入任何的运算符,所以其实也为 IMPOSSIBLE

除此之外,这是一道dfs暴力深搜的水题,甚至没有地方需要剪枝,代码非常简单,原创。

#include<bits/stdc++.h>
using namespace std;
string s;
string symbol = " *+-";
int len;
string sym; //记录符号
vector<int> num;
vector<char> symboll;

const int maxn = 9 + 3;

bool cal() {
	int size = num.size();
	for (int i = 0; i < size - 1; i++) {
		if (symboll[i] == '*') {
			num[i + 1] = num[i] * num[i + 1];
			num[i] = -1;
			symboll[i] = ' ';
		}
	}
	vector<int> num1;
	vector<char> symbol2;
	for (int i = 0; i < size; i++) {
		if (i && symboll[i - 1] != ' ') symbol2.push_back(symboll[i - 1]);
		if (num[i] != -1) num1.push_back(num[i]);
	}
	size = num1.size();
	int e = num1[0];
	if (size == 2 && num1[0] == 2100 && num1[1] == 100) {
		int k = 1;
	}
	for (int i = 1; i < size; i++) {
		if (symbol2[i - 1] == '+') e += num1[i];
		else e -= num1[i];
	}
	//cout << " " << e;
	//cout << endl;
	return e == 2000;
}

bool check() {
	num.clear();
	symboll.clear();
	int e = 0;
	for (int i = 0; i < len; i++) {
		e *= 10;
		e += s[i] - '0';
		if (sym[i] != ' ') {
			num.push_back(e);
			e = 0;
			symboll.push_back(sym[i]);
		}
	}

	int cnt = 0;
	for (auto n : num) {
		if (n == 0) {
			cnt++;
			continue;
		}
		while (n) {
			n /= 10;
			cnt++;
		}
	}
	/*
	for (auto& n : num) {
		cout << n << " ";
	}
	for (auto& ch : symboll) {
		cout << ch << " ";
	}
	cout << endl;
	*/
	if (cnt != len) return false;
	return cal();
}

void print() {
	cout << "  ";
	for (int i = 0; i < len; i++) {
		cout << s[i];
		if (sym[i] != ' ' && i != len - 1) cout << sym[i];
	}
	cout << "=" << endl;
}

bool dfs(int d) {
	if (d == len - 1) {
		if (check()) {
			print();
			return true;
		}
		return false;
	}
	bool flag = false;
	for (int i = 0; i < 4; i++) {
		sym[d] = symbol[i];
		if (dfs(d + 1)) flag = true;
	}
	return flag;
}

int main() {
	// freopen("in.txt", "r", stdin);
	// freopen("out.txt", "w", stdout);
	ios::sync_with_stdio(false);
	cin.tie(0);
	int kase = 0;
	while (cin >> s) {
		if (s == "=") break;
		cout << "Problem " << ++kase << endl;
		if (s == "2000=") {
			cout << "  IMPOSSIBLE" << endl;
			continue;
		}
		len = s.length() - 1;
		sym.resize(maxn);
		if (!dfs(0)) {
			cout << "  IMPOSSIBLE" << endl;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值